[英]How to use onchange in HTML
I have two text box in html ie: 我在html中有两个文本框,即:
<input type="text" value="" id="a" name="a" />
<input type="text" value="" readonly="true" id="b" name="b" />
Now if i enter only a number in element id "a" then the product of inserted number by 2 will be appear in element id "b". 现在,如果我仅在元素ID“ a”中输入数字,则插入数字乘以2的乘积将出现在元素ID“ b”中。
Like: While im typing a number let say 11 in element "a" then on the same time 11*2 ie: 22 will appear in element "b" and if enter backspace or delete any number on the same time change will appear in element "b". 就像:我在输入数字时,在元素“ a”中说11,然后在同一时间11 * 2,即:22将出现在元素“ b”中,如果同时输入Backspace或删除任何数字,则更改将出现在元素中“b”。
To get my required result i create a function like 为了获得所需的结果,我创建了一个函数
onchange = function totalAmount()
{
var value = $("#a").val();
if ( (value > 0) && (value != "") )
{
$("input:text[name=b]").val(2 * value);
}
else
{
$("input:text[name=getCredit]").val("");
}
};
It fulfill 80% of my requirement as it will make change in element "b" if i click on any were after insert a number. 它满足了我80%的要求,因为如果我在插入数字后单击任何元素,它将在元素“ b”中进行更改。
I see that you are using jQuery. 我看到您正在使用jQuery。 You could bind to the
change
event of the textbox: 您可以绑定到文本框的
change
事件:
$('input:text[name=a]').change(function() {
// invoked when the value of input name="a" changes
// get the new value
var value = $(this).val();
// update the value of input name="b"
$('input:text[name=b]').val(2 * value);
});
This event will be raised when the input loses focus. 输入失去焦点时将引发此事件。 You could also take a look at
keypress
and keyup
events. 你也可以看看
keypress
和keyup
事件。
i think using the onkeyup event might help 我认为使用onkeyup事件可能会有所帮助
<input type="text" value="" id="a" name="a" onkeyup="calcTotalAmount()" />
<input type="text" value="" readonly="true" id="b" name="b" />
<script>
function calcTotalAmount() {
var a = document.getElementById("a");
var b = document.getElementById("b");
if (!isNaN(a.value)) {
b.value = a.value * 2;
}
}
</script>
Why onkeyup? 为什么要onkeyup?
Onkeydown event fires when key is pressed, onkeyup event fires when key is released and the event onkeypress fires if the onkeydown is followed by onkeyup, 按下键时会触发Onkeydown事件,释放键时会触发onkeyup事件,如果在onkeydown之后跟随onkeyup,则会触发onkeypress事件,
and in the time of onkeydown the input field does not containt the value yet. 并且在onkeydown时,输入字段尚未包含该值。
If you want a call back on every key press you can use the onKeyPress attribute. 如果要在每个按键上都进行回调,则可以使用onKeyPress属性。
(If you are using a library like JQuery/prototype/etc there is probably a nice way of observing a field using the library) (如果您使用的是诸如JQuery / prototype / etc之类的库,则可能有一种使用该库观察字段的好方法)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.