2

This is my code:

$("input[type=text]").on("input", function(){
  console.log("input event fired.");
})

$("input[type=button]").on("click", function(){
  var event = new Event('input');
 $("input[type=text]").dispatchEvent(event);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="write .." />
<input type="button" value="emulate input event" />

As you can see, when you write something into the input, input event works as well. How can I emulate that event when you click on the button?

0

4 Answers 4

2

jQuery uses trigger

If you want to use dispachtEvent, you need the DOM element.

$("input[type=text]").on("input", function(){
  console.log("input event fired.");
})

$("input[type=button]").on("click", function() {
  // EITHER
  $("input[type=text]").trigger("input");
  // OR
  var event = new Event('input');
  $("input[type=text]")[0].dispatchEvent(event); // DOM 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="text" placeholder="write .." />
<input type="button" value="emulate input event" />

Sign up to request clarification or add additional context in comments.

Comments

1

$("input[type=text]").on("input", function(){
  console.log("input event fired.");
})

$("input[type=button]").on("click", function(){
 $("input[type=text]").trigger("input");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="write .." />
<input type="button" value="emulate input event" />

Comments

0

You could simply use the .trigger() method to fire the event by name like :

$("input[type=button]").on("click", function(){
    $("input[type=text]").trigger("input");
})

$("input[type=text]").on("input", function() {
  console.log("input event fired.");
})

$("input[type=button]").on("click", function() {
  $("input[type=text]").trigger("input");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="write .." />
<input type="button" value="emulate input event" />

Comments

0

In jQuery you can just call the event type on the element.

To invoke a click event on an element do:

$("foo").click();

For an input field, the best option is usually to

$("foo").change();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.