简体   繁体   English

如何使用JavaScript更新按键上的文本框

[英]How to update a textbox on key press using JavaScript

Is there a way to update the value of a textbox on every key press? 有没有办法在每次按键时更新文本框的值?

I'm doing currency conversion. 我正在进行货币兑换。 So, there are two textboxes, one for the user to input the value while the other will automatically show the converted amount on every key press. 因此,有两个文本框,一个用于用户输入值,另一个将在每次按键时自动显示转换后的金额。

Should I use a for loop? 我应该使用for循环吗? But what should I loop? 但我应该循环什么呢?

The textboxes in the following for loop should be able to do its individual row conversion 以下for循环中的文本框应该能够进行单独的行转换

<% for(int i=0; i<2; i++) { %>
 <td><input type="text" id= "amount" name="amount<%=i%>" /></td>

 <td><input type="text" id= "convertedAmount" name="convertedAmount<%=i%>" readonly/></td>
<%}%>

How should I get started in attempting this task? 我该如何开始尝试这项任务?

Thanks in advance for any possible help. 在此先感谢任何可能的帮助。

onkeyup is best suited for your task: onkeyup最适合您的任务:

Type amount $: <input type='text' id='amount' onkeyup="updateConverted()" >
<br>
Converted: <input type='text' id='converted' >

JavaScript function: JavaScript函数:

function updateConverted() {
    var conversionRate = 1.5;
    document.getElementById('converted').value =
                       document.getElementById('amount').value * conversionRate;
}

Demo here . 在这里演示


Update (JSP for loop): 更新(JSP for循环):

In the case of your for loop, you can just use the following jQuery code (no need to change the HTML): 对于for循环,您可以使用以下jQuery代码(无需更改HTML):

$('input[name=amount]').each(function (_, value) {
    $(value).keyup(function () {
        var rate = 1.5;
        var convAmount = $(this).val() * rate;
        $(this).parent().next().children('input[name=convertedAmount]').val(convAmount);
    });
});

See demo here . 在这里看演示

Note: Your for loop is generating duplicated IDs. 注意:您的for循环正在生成重复的ID。 If possible, avoid that as it is invalid HTML. 如果可能,请避免这种情况,因为它是无效的HTML。

Simple using jQuery: 使用jQuery很简单:

<input type="text" name="t1" id="t1" value="" onkeypress="calculation()" />

<input type="text" name="converted" id="converted" value="" />

<script>
function calculation() {
   var price = 'here is your formula';
   $('#converted').val(price);
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM