jQuery identifying change of own jQuery
When you click on "place", the field is filled with the information" changed", but when this happens, the next change
does not identify this change.
In practice this does not work, how can I make it work?
HTML
<button id="botao">Colocar</button>
<input id="campo">
JQuery
$('#botao').click(function(){
$('#campo').val('mudou');
})
$('#campo').change(function() {
alert('mudou mesmo');
});
4 answers
As already mentioned, changing the value via Javascript does not trigger the change event.
An alternative is to run the desired code along with changing the value rather than relying on the event.
Another approach is to manually run the event after the change using the change()
or trigger("change")
method.
Example:
$('#botao').click(function(){
$('#campo').val('mudou');
$('#campo').change(); // ou trigger("change")
})
$('#reset').click(function(){
$('#campo').val('');
$('#campo').change(); // ou trigger("change")
})
$('input').change(function() {
alert('mudou mesmo');
});
See jsfiddle with change()
or with trigger()
.
Note : caution when invoking methods that invoke events inside methods that are called by events not to end up in an infinite loop.
The change
method only listens to the onchange
event from the browser, it is not activated when the value changes programmatically. An alternative would be to invoke change
manually via the command trigger
:
$('#botao').click(function(){
$('#campo').val('mudou').trigger('change');
})
$('#campo').change(function() { // Nota: o id é "campo", não "input"
alert('mudou mesmo');
});
Example . This is a common doubt, but unfortunately there is no way to get a listener to detect changes to the value
property of input
made programmatically. The closest thing I could find is DOMAttrModified
, but besides it not being supported by most browsers, it is only triggered on changes to the Attributes, and value
is a property.
You don't have a input
with the id="input"
. Either you correct the same @bfavaretto spoke, or on the propio button click you can call the input prompt. Example:
$('#botao').click(function(){
$('#campo').val('mudou');
if($('#campo').val()=='mudou')
alert('mudou mesmo');
})
Form:
input type="text" name="campo" id="campo" value="1234"
input type="text" name="valor" id="valor" value=""
input type="submit" id="gravar" value="gravar alteracao"
Script:
$(document).ready(function(){
$('#campo').focus();
$('#gravar').css('display','none');
$('#campo').blur(function(){
$('this').val().trigger('change');
})
$('#campo').change(function() {
alert('o valor de campo foi alterado');
$('#gravar').css('display','block');
});
});