programatically changing value in input field perform some task - javascript

HTML
<input id="testinput" type="text"></input>
JS
$('#testinput').change(function (){
change();
});
function change(){
alert();
}
$('#testinput').val('new val');
Link
By typing in input and losing focus it works, but if a change of the input field is triggered by jquery, it does not work.
$('#testinput').val('new val').trigger('change'); not required.

From MDN (bolded by me):
The change event is fired for input, select, and textarea
elements when a change to the element's value is committed by the
user. Unlike the input event, the change event is not necessarily
fired for each change to an element's value.
You will need to manually trigger the change event if you are changing the value programmatically.
I suppose if you are hellbent on not manually firing the change event, you could override jQuery's val ($.fn.val) method to do it for you:
var originalVal = $.fn.val;
$.fn.val = function() {
if(arguments.length) {
originalVal.apply(this, arguments);
this.trigger('change');
return this;
}
return originalVal.call(this);
}
http://jsfiddle.net/ybj1zjhk/4/

will fire the alert whenever you type something
$('#testinput').keyup(function (){
change();
});
function change(){
alert();
}
$('#testinput').val('new val');
Or you can trigger the change event whenever you do something that requires you to have the change event fire https://jsfiddle.net/owoemcg2/
$('#testinput').change(function (){
change();
});
function change(){
alert();
}
$("#mybutton").click(function(){
$('#testinput').val('new val');
$("#testinput").trigger("change");
});

Related

Bypass onclick event and after excuting some code resume onclick

I have the below html button which have onclick event
<button onclick="alert('button');" type="button">Button</button>
and the following js:
$('button').on('click', function(){
alert('jquery');
});
After executing some js code by jQuery/Javascript, i want to continue with the button onclick handler e.g: jquery alert first and than button alert.
i tried so many things like "remove attr and append it after executing my code and trigger click (it stuck in loop, we know why :) )" and "off" click. but no luck.
is it possible via jQuery/javascript?
any suggestion much appreciated
Thanks
A little bit tricky. http://jsfiddle.net/tarabyte/t4eAL/
$(function() {
var button = $('#button'),
onclick = button.attr('onclick'); //get onclick value;
onclick = new Function(onclick); //manually convert it to a function (unsafe)
button.attr('onclick', null); //clear onclick
button.click(function() { //bind your own handler
alert('jquery');
onclick.call(this); //call original function
})
});
Though there is a better way to pass params. You can use data attributes.
<button data-param="<%= paramValue %>"...
You can do it this way:
http://jsfiddle.net/8a2FE/
<button type="button" data-jspval="anything">Button</button>
$('button').on('click', function () {
var $this = $(this), //store this so we only need to get it once
dataVal = $this.data('jspval'); //get the value from the data attribute
//this bit will fire from the second click and each additional click
if ($this.hasClass('fired')) {
alert('jquery'+ dataVal);
}
//this will fire on the first click only
else {
alert('button');
$this.addClass('fired'); //this is what will add the class to stop this bit running again
}
});
Create a separate javascript function that contains what you want to do when the button is clicked (i.e. removing the onclick attribute and adding replacement code in its own function).
Then call that function at the end of
$('button').on('click', function(){
alert('jquery');
});
So you'll be left with something like this
function buttonFunction()
{
//Do stuff here
}
$('button').on('click', function()
{
alert('jquery');
buttonFunction();
});
<button type="button">Button</button>

Need to store input value to variable on change

I am trying to store the value of an input into a variable. For now, I want to just paste the input value into a span element so I can know that it works. However I cannot get it work in my JSFIDDLE. Any suggestions?
HTML:
<label>Advertising Budget:</label>
<input id="advertising" onchange="updateAdvertising(this.value)"> </input>
<span id="test">xxx</span>
Javascript:
function updateAdvertising(adv){
document.getElementById('test').innerText = adv;
}
JSFIDDLE: http://jsfiddle.net/6J4MN/
innerHTML is more compatible, also change fiddle to head instead of onload
Here is a neater solution
Live Demo
window.onload=function() {
document.getElementById("advertising").onchange=function(){
document.getElementById('test').innerHTML = this.value;
}
}
Since onchange needs a blur to trigger, use onkeyup for immediate change:
Live Demo
window.onload=function() {
document.getElementById("advertising").onkeyup=function(){
document.getElementById('test').innerHTML = this.value;
}
}
Note the "OnChange" event for the text box will fire once you hit enter or leave the text box. If you change the event to, say keyup, it will update the span after every letter you type.
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
};
addEvent(document.getElementById('advertising')
, 'change'
, function () { updateAdvertising(this.value); }
);
var updateAdvertising = function(adv){
document.getElementById('test').innerText = adv;
};
};
</script>

jQuery, how to capture when text input has changed as a result of another event

I have a text input that is updated as a result of a button event. I would like to detect when the value in the text input has changed. See the example below:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#text').bind("input change paste", function(){
console.log("text changed");
// do something
});
$('#click').click (function(){
$('#text').val('something');
});
});
</script>
<body>
<input id='text' type='text'>
<input id='click' type='button' value='click'>
</body>
Later on, that button will trigger a calender so the user select a date/time which will update the text input. Since the calender is part of a library we I don't want to change it. I would like to detect when the text field gets a new value.
thanks!
I think what you're referring to is
$("#text").on("change", function(){});
take a look at this post
Since the date/time picker library you are using doesn't raise any sort of change or input event, the only way to reliable tell if the value has changed is to watch with a timer and raise the change event yourself. The following is one way to do this:
// check for changes every 100 ms
setInterval(function() {
var lastVal = $('#text').data('last-value');
if (typeof lastVal === 'undefined') {
lastVal = $('#text').val();
$('#text').data('last-value', lastVal);
}
if (lastVal !== $('#text').val()) {
$('#text').change(); // trigger the change event
}
}, 100);
// setup your change handler
$('#text').on("input change paste", function() {
// before doing anything else, set the last-value data property
$('#text').data('last-value', $('#text').val());
// do something ...
console.log('changed!');
});
// now programmitically updating the $('#text') element will result
// in your change handler being triggered
$('#click').click (function(){
$('#text').val('something');
});

Keeping the submit button disabled until a change is made

In my VB.NET project, I have a UI with some text input fields and a save/submit button. I want the save button to be in a disabled state on page load, and remain that way until a change is made to one of the inputs. And the save button should get disabled again if the values entered by the user are the same as they were at page load. So basically, the save button should be enabled only when there is an actual change.
How can I do this using jquery?
$(':input').change(
function(){
$("#submitButtonId").prop("disabled",false);
}
);
since you said it is dynamic, use on.
$(document).on("change", ":input",
function(){
$("#submitButtonId").prop("disabled",false);
}
);
You can handle that in the change event
$('input[type="text"]').on('change', function() {
// Change event fired..
$('input[type="submit"]').prop('disabled', false);
});
//This will bind all existing and dynamically added selects onChange to the handler
$(document).on('change', function(e) {
onChangeHandler();
}
// handle the event
function onChangeHandler() {
if (checkValues()) {
$('#yourButtonId').prop("disabled", false);
}
else {
$('#yourButtonId').prop("disabled", true);
}
}
// check all values against originals - data-* attributes are a good way to store data on
// an element. So have you can have:
<select id="id1" data-originalvalue="myValue"></select>
// compare the current value to the original value - if any one of them differ, return
// true
function checkValues() {
$.each($('select[data-originalvalue]'), function() {
if ($(this).val() !== $(this).attr(data-originalvalue){
return true;
}
return false;
});
}

Do not fire one event if already fired another

I have a code like this:
$('#foo').on('click', function(e) {
//do something
});
$('form input').on('change', function(e) {
//do some other things
));
First and second events do actually the same things with the same input field, but in different way. The problem is, that when I click the #foo element - form change element fires as well. I need form change to fire always when the content of input is changing, but not when #foo element is clicked.
That's the question )). How to do this?
Here is the code on jsfiddle: http://jsfiddle.net/QhXyj/1/
What happens is that onChange fires when the focus leaves the #input. In your case, this coincides with clicking on the button. Try pressing Tab, THEN clicking on the button.
To handle this particular case, one solution is to delay the call to the change event enough check if the button got clicked in the meantime. In practice 100 milisecond worked. Here's the code:
$().ready(function() {
var stopTheChangeBecauseTheButtonWasClicked = false;
$('#button').on('click', function(e) {
stopTheChangeBecauseTheButtonWasClicked = true;
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
var self = this;
setTimeout(function doTheChange() {
if (!stopTheChangeBecauseTheButtonWasClicked) {
$(self).val($(self).val() + ' - changed!');
} else {
stopTheChangeBecauseTheButtonWasClicked = false;
}
}, 100);
});
});
And the fiddle - http://jsfiddle.net/dandv/QhXyj/11/
It's only natural that a change event on a blurred element fires before the clicked element is focused. If you don't want to use a timeout ("do something X ms after the input was changed unless in between a button was clicked", as proposed by Dan) - and timeouts are ugly - you only could go doing those actions twice. After the input is changed, save its state and do something. If then - somewhen later - the button is clicked, retrieve the saved state and do the something similar. I guess this is what you actually wanted for your UI behaviour, not all users are that fast. If one leaves the input (e.g. by pressing Tab), and then later activates the button "independently", do you really want to execute both actions?
var inputval = null, changedval = null;
$('form input').on('change', function(e) {
inputval = this.value;
// do some things with it and save them to
changedval = …
// you might use the value property of the input itself
));
$('#foo').on('click', function(e) {
// do something with inputval
});
$('form …').on('any other action') {
// you might want to invalidate the cache:
inputval = changedval;
// so that from now on a click operates with the new value
});
$(function() {
$('#button').on('click', function() {
//use text() not html() here
$('#wtf').text("I don't need to change #input in this case");
});
//fire on blur, that is when user types and presses tab
$('#input').on('blur', function() {
alert("clicked"); //this doesn't fire when you click button
$(this).val($(this).val()+' - changed!');
});
});​
Here's the Fiddle
$('form input').on('change', function(e) {
// don't do the thing if the input is #foo
if ( $(this).attrib('id') == 'foo' ) return;
//do some other things
));
UPDATE
How about this:
$().ready(function() {
$('#button').on('click', function(e) {
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
// determine id #input is in focus
if ( ! $(this).is(":focus") ) return;
$(this).val($(this).val()+' - changed!');
});
});

Categories

Resources