Fire oninput event with jQuery
I have an oninput event on a textarea to check the height and resize it. Now I need to edit the value sometimes. I do this just by editting the val() in jQuery, but that does not trigger the oninput event. Is there any way to trigger the oninput event programatically with jQuery?
Solution 1:
Use .on('input')
. For example:
$('textarea').on('input', function() {
text = $('textarea').val();
$('div').html(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea placeholder="Type something here"></textarea>
<div></div>
Solution 2:
It is a bit too late, but for future reference, there is the .trigger method.
$("#testArea").on("input", function(e) {
$("#outputArea").text( $(e.target).val() )
});
$("#testArea").val("This is a test");
$("#testArea").trigger("input");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="testArea" type="text" />
<div id="outputArea"></div>
Solution 3:
You can simply invoke it, e.g.:
$("input")[0].oninput = function () {
alert("hello");
};
$("input")[0].oninput();
...but as @Sammaye points out, jQuery has no explicit "oninput" handler, so you'll have to use POJS.
Demo on JS Fiddle.