javascript JS改变输入值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18612794/
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
JS change input value
提问by vicR
My problem is: I have two input boxes one for a code and one for a price:
我的问题是:我有两个输入框,一个是代码,一个是价格:
<input class="style" name="code" id="code" type="text">
<input class="style" name="price" id= "price" type="text" value="€ 15,00" readonly="readonly">
Now i want to change the price by code (like a check from a code array [code1][code2]. result to code1 = price/2 and code2 = price/4 ) This i want to check by a script in real time or befor the post (on submit). This this possible when yes how? Or is there another better way to do this ?
现在我想通过代码更改价格(例如从代码数组 [code1][code2] 中检查。结果为 code1 = price/2 和 code2 = price/4 )我想通过脚本实时检查或在发布之前(提交时)。这可能是怎么回事?还是有另一种更好的方法来做到这一点?
I have:
我有:
while(true)
{
var code = document.getElementById("code").value;
var codes = new Array("promo1", "promo2");
for (var i=0; i<codes.length; i++) {
if (codes[i] == code) {
document.getElementById("price").value = "5";
}
}
}
and my input fields are obviously in a form-field but the value doesnt change, but why ? I dont have to change in real time it would be ok if the post sends the new value...any solutions/better ideas/hints ? I know there is JQuery a better approach but it shouldn't be a problem with js.
并且我的输入字段显然在表单字段中但值没有改变,但为什么呢?我不必实时更改,如果帖子发送新值就可以了……任何解决方案/更好的想法/提示?我知道 JQuery 有更好的方法,但它不应该是 js 的问题。
fiddle link:
jsfiddle.net/vicR/4Mtbr
小提琴链接:
jsfiddle.net/vicR/4Mtbr
回答by Daniel Varab
This can be obtained easily in many ways, specially if one takes use of libraries or frameworks, but with pure javascript it should be done as so:
这可以通过多种方式轻松获得,特别是如果使用库或框架,但使用纯 javascript 应该这样做:
while(true) {
var code = document.getElementById("code").value
//now check for valid code in some sort of map or array
//REMEMBER javascript supports string indexed arrays such as arr["#45"]
if(code == validatorFunctionOrCode) { //obviously pseudo
document.getElementById("price").value = "your corresponding price to the code"
}
}
- This is all checked dynamically and before you hit the submit button.
- 在您点击提交按钮之前,所有这些都是动态检查的。
With this said I would strongly recommend Angular.jssince it supports databinding (example - databinding)
话虽如此,我强烈推荐Angular.js,因为它支持数据绑定(示例 -数据绑定)
回答by long.luc
It is done with some jQuery code:
它是通过一些 jQuery 代码完成的:
$('#form').submit(function() {
$('#price').val(value_you_want_to_change);
});