Modify element via JavaScript and "warn" the page that the element has been modified

1

$(document).ready(function(){
  $("#myTextarea").change(function(){
    alert("text area changed");
  });
  
  //$("#myTextarea").keydown(function(){
    //alert("text area changed");
  //});
});
 
setTimeout(function() {
  $("#myTextarea").val("changed");
  $("#myTextarea").blur();
}, 1000);
<!DOCTYPE html>
<body>
  <textarea id="myTextarea" rows="4" cols="20"></textarea>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>

I need to know why the above code does not work, theoretically, textarea when modified within setTimeout , should run the change function code, but it does not execute and I need to know why and how I solve it .

    
asked by anonymous 11.09.2017 / 16:48

3 answers

1

Trigger a trigger instead of blur () ...

$(document).ready(function(){
  $("#myTextarea").change(function(){
    alert("text area changed");
  });
  
  //$("#myTextarea").keydown(function(){
    //alert("text area changed");
  //});
});
 
setTimeout(function() {
  $("#myTextarea").val("changed");
  //$("#myTextarea").blur();
  $("#myTextarea").trigger("change");
}, 1000);
<!DOCTYPE html>
<body>
  <textarea id="myTextarea" rows="4" cols="20"></textarea>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
    
11.09.2017 / 17:00
0

Just after the change in textarea, use the trigger method, and call the event you need in the change case, example :

$(document).ready(function(){
  $("#myTextarea").change(function(){
    alert("text area changed");
  });
});
 
setTimeout(function() {
  $("#myTextarea").val("changed").trigger('change');
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textareaid="myTextarea" rows="4" cols="20"></textarea>

11.09.2017 / 17:02
0

This event is triggered only when the user changes the content of textarea and the element loses focus ( link ).

You can fire the event using jquery as follows:

$("#myTextarea").change(); ( link )

$(document).ready(function(){
  $("#myTextarea").change(function(){
    alert("text area changed");
  });
  
  //$("#myTextarea").keydown(function(){
    //alert("text area changed");
  //});
});
 
setTimeout(function() {
  $("#myTextarea").val("changed");
  $("#myTextarea").change();
}, 1000);
<!DOCTYPE html>
<body>
  <textarea id="myTextarea" rows="4" cols="20"></textarea>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
    
11.09.2017 / 17:04