Manually change event not fired Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Manually change event not fired without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have this demo html and JS:

$('#inputs').on('change keypress keyup paste', 'input, select, textarea', function (event) {
    alert(event);
  console.log(event);          
});


$('button').on('click', function (event) {
  console.log("click");
  var input = document.getElementById('number');
    if("createEvent" in document) {
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent("change", false, true);
        input.dispatchEvent(evt);
    } else {
        input.fireEvent("onchange");
    }
            
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputs">
  <input name="number" type="number" id="number" value="">  
</div>

<button type="button">CLICK</button>

Which not work as expected. alert and console.log not show anything.

I just want click button behind input and send to input change event. What is wrong with my simple code?

Answer

Check the code below. I have used a different way of firing the event. Now if you click the button, change event gets fired on the input.

$('#inputs').on('change keypress keyup paste', 'input, select, textarea', function (event) {
  console.log('Change event');
});


$('button').on('click', function (event) {
  console.log('Click event');
  
  var input = document.getElementById('number');
  var event = new Event('change', {
    bubbles: true,
    cancelable: true
  });
  
  input.dispatchEvent(event);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputs">
  <input name="number" type="number" id="number" value="">  
</div>

<button type="button">CLICK</button>
We are here to answer your question about Manually change event not fired - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji