输入,onchange事件在手动设置值时不会触发

时间:2022-11-05 15:18:38

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/

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

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

但事件“输入”不会按下按钮。而“改变”也无效。

HTML:

HTML:

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

Javascript:

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

有解决方案的人吗?谢谢 :)

3 个解决方案

#1


2  

First, change the on handler to use change like

首先,更改on处理程序以使用更改

$("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

小提琴

#2


1  

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.

我认为$(“输入”)。val(1)应该改为$(“input”)。val(1).trigger('input');.您正在侦听输入事件,因此在更改应触发事件的值之后。

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

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

#3


1  

Try this:

尝试这个:

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

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

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

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.

因此,范围滑块通常通过更改值进行更新。如果设置了值,AmmarCSE解决方案仅触发。

#1


2  

First, change the on handler to use change like

首先,更改on处理程序以使用更改

$("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

小提琴

#2


1  

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.

我认为$(“输入”)。val(1)应该改为$(“input”)。val(1).trigger('input');.您正在侦听输入事件,因此在更改应触发事件的值之后。

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

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

#3


1  

Try this:

尝试这个:

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

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

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

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.

因此,范围滑块通常通过更改值进行更新。如果设置了值,AmmarCSE解决方案仅触发。