Cracker0dks
Cracker0dks

Reputation: 2490

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 :)

Upvotes: 2

Views: 2878

Answers (3)

Valentin Palkovic
Valentin Palkovic

Reputation: 154

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.

Upvotes: 2

Krasimir
Krasimir

Reputation: 13549

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/

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30607

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

Upvotes: 4

Related Questions