在 jQuery 中获取输入数字的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43169407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the value of a input number in jQuery
提问by Louis 'LYRO' Dupont
I'm working on a form, and I want to get in real time the current value of an input field of type number, as this one :
我正在处理一个表单,我想实时获取类型为 number 的输入字段的当前值,如下所示:
$(":input").bind('keyup mouseup', function () {
var coins = $("#coins").val();
$("#reward").text(coins);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="coins" type="number" name="coins" value="1" max="999" min="1">
<p id="potential">Potential reward : <b id="reward"></b></p>
But nothing happen when I run it. It says that the value of coins is null. I don't know what I am doing wrong... Anyone could help ?
但是当我运行它时什么也没有发生。它说硬币的价值是空的。我不知道我做错了什么......任何人都可以帮忙吗?
采纳答案by zeus
You could use the following:
您可以使用以下内容:
$(document).on('input', '#coin', function(){
var coins = $("#coins").val();
$("#reward").text(coins);
})
回答by charlietfl
Code shown works fine when user makes edits.
当用户进行编辑时,显示的代码工作正常。
If you need it to display when page loads just trigger one of the events
如果您需要它在页面加载时显示,只需触发其中一个事件
$(":input").on('keyup mouseup', function () {
var coins = $("#coins").val();
$("#reward").text(coins);
}).trigger('mouseup');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="coins" type="number" name="coins" value="1" max="999" min="1">
<p id="potential">Potential reward : <b id="reward"></b></p>
Note that bind()
is deprecated in favor of using on()
请注意,bind()
不赞成使用on()