javascript Javascript根据另一个文本框的输入更新文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10541449/
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
Javascript to update a textbox based on the input of another textbox
提问by Brian Yee
I basically want to use javascript to have 2 textboxes that depend on each other. For example if I input a number x in textbox1, I want textbox2 to instantly update with x*2. If I input x into textbox2, I want textbox1 to be automatically updated with x/2. These values will always be numbers.
我基本上想使用 javascript 来拥有 2 个相互依赖的文本框。例如,如果我在 textbox1 中输入一个数字 x,我希望 textbox2 立即更新为 x*2。如果我将 x 输入到 textbox2,我希望 textbox1 自动更新为 x/2。这些值将始终是数字。
Edit: so here is my html file. Can anyone give me a hint to why it's not working?
编辑:这是我的 html 文件。谁能给我一个提示为什么它不起作用?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$("#text1").keyup(function(){
$("#text2").val($(this).val() * 2);
});
$("#text2").keyup(function(){
$("#text1").val($(this).val() / 2);
});
</script>
</head>
<body>
<input type="text" name="text1" size=3 maxlength=6>
<input type="text" name="text2" size=3 maxlength=6>
</body>
</html>
回答by rjz
In the very simple case, this should do it (fiddle here):
在非常简单的情况下,应该这样做(在这里小提琴):
// in a <script>:
window.update = function() {
var one = document.getElementById('one'),
two = document.getElementById('two');
two.value = parseInt(one.value) * 2;
}?
<!-- in your HTML: -->
<input id="one" type="text" onchange="update();" />
<input id="two" type="text" />?
回答by Elliot Bonneville
$("#textbox1").onkeyup(function() {
$("#textbox2").val($(this).val() * 2);
});
$("#textbox2").onkeyup(function() {
$("#textbox1").val($(this).val() / 2);
});
回答by voscausa
Use an onchange event or a jquery change callback to update the other boxes.
使用 onchange 事件或 jquery 更改回调来更新其他框。
回答by David Kirby
I'm unable to test out the exact code you'll need for this right now, but the basic idea is to put an OnKeyUp event on each box and modify the other box through the script (using getElementById or whichever method you like)
我现在无法测试您现在需要的确切代码,但基本思想是在每个框上放置一个 OnKeyUp 事件并通过脚本修改另一个框(使用 getElementById 或您喜欢的任何方法)
I will try to put together some code when I can if someone else doesn't get to it first.
如果其他人没有先得到它,我会尽可能地将一些代码放在一起。
回答by Sagar Dixit
In the this case, this should do it : http://jsfiddle.net/du09jhpd/
在这种情况下,应该这样做:http: //jsfiddle.net/du09jhpd/
window.update = function() {
var one = document.getElementById('one'),
two = document.getElementById('two');
two.value = parseInt(one.value) * 2;
}
window.update1 = function() {
var one = document.getElementById('one'),
two = document.getElementById('two');
one.value = parseInt(two.value) / 2;
}