简体   繁体   中英

input, onchange event dont fire when value is set manually

I want to catch the event on the range slider even if i press a button and change the Value by:

$("input").val(1);

http://jsfiddle.net/BaEar/188/

But the event "input" dont fire by button press. And "change" is also not working.

HTML:

<input type="range">
<button>Change</button>
<div id="output"></div>

Javascript:

$("input").on("input", function() { //Does not fire on button click :(
    $("#output").text($(this).val());
});

$("button").click(function() {
   $("input").val(1); 
});

Anyone with a solution ? Thanks :)

First, change the on handler to use change like

$("input").on("change", function() { 
    $("#output").text($(this).val());
});

Second, manually trigger it in the click handler like

$("button").click(function() {
   $("input").val(1); 
    $("input").trigger("change");
});

fiddle

I think $("input").val(1) should be changed to $("input").val(1).trigger('input'); . You are listening for input event so after changing the value that event should be fired.

jsfiddle -> http://jsfiddle.net/BaEar/191/

Try this:

$("input").on("input change", function() {
    $("#output").text($(this).val());
});

$("button").click(function() {
   $("input").val(1);
   $("input").change();
});

http://jsfiddle.net/BaEar/192/

So the range slider is normally updating by changing the value. AmmarCSE solution only triggers, if a value is set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM