jQuery identifying jQuery's own change

5

When you click on "put", the field is populated with "changed" information, but when this happens, 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');
});

link

    
asked by anonymous 10.02.2014 / 14:47

4 answers

8

As already mentioned, changing the value via Javascript does not trigger the change event.

An alternative is to execute the desired code along with changing the value instead of relying on the event.

Another approach is to manually execute the event after the change using the method change() or trigger("change") .

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 com trigger() .

Note : Be careful when invoking methods that invoke events within methods that are called by events to not end up in an infinite loop.

    
10.02.2014 / 14:55
4

The change method only listens to the onchange event of the browser, it is not activated when the value changes programmatically. An alternative would be to invoke change manually using the trigger command:

$('#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 question, but unfortunately there is no way to put a listener that detects changes to the value property of input made programmatically . The closest I could find is DOMAttrModified , but since it is not supported by most browsers, it only fires in changes in attributes , and value is a property .

    
10.02.2014 / 14:54
1

You do not have input with id="input" . Or you correct the same @bfavaretto spoke, or in the own button click you can call the input alert. Example:

$('#botao').click(function(){
    $('#campo').val('mudou');
    if($('#campo').val()=='mudou') 
           alert('mudou mesmo');
})
    
10.02.2014 / 14:53
0

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');  
   });  
});  
    
12.02.2015 / 20:16