Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire JQuery change event when input value changed programmatically?

I want to fire the JQuery change event when the input text is changed programmatically, for example like this:

$("input").change(function(){      console.log("Input text changed!");  });  $("input").val("A");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <input type='text' />

But it doesn't work. How can I make this work?

like image 664
Mohammad Avatar asked Nov 24 '15 07:11

Mohammad


People also ask

How can I trigger an Onchange event manually in JavaScript?

document. querySelector('#test'). addEventListener('change', () => console. log("Changed!"))

How do you trigger an event when a textbox is filled with value?

change function , but that needs to be done only if the the value is changed using the button . $("#address"). change will trigger if you perform any change in text field. If you want to trigger alert only when button click why you don't use alert inside button click function.

What event can you listen to when the value is changed by JavaScript?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed. Tip: This event is similar to the oninput event.

How do I trigger a change event on page load?

Jquery trigger change event can be called with a few simple line of code. Let's take an example, jquery on page load or jquery after page load, you just want to call an function which is onchange function of jquery.


2 Answers

change event only fires when the user types into the input and then loses focus.

You need to trigger the event manually using change() or trigger('change')

$("input").change(function() {    console.log("Input text changed!");  });  $("input").val("A").change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  <input type='text' />
like image 188
Pranav C Balan Avatar answered Sep 24 '22 18:09

Pranav C Balan


The event handler .change() behaves like a form submission - basically when the value changes on submit the console will log. In order to behave on text input you would want to use input, like below:

$("input").on('input', function(){      console.log("Input text changed!");  });  $("input").val("A");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <input type='text' />
like image 26
kawnah Avatar answered Sep 24 '22 18:09

kawnah