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? But what should I loop?
The textboxes in the following for loop should be able to do its individual row conversion
<% 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.
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? But what should I loop?
The textboxes in the following for loop should be able to do its individual row conversion
<% 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.
Share Improve this question edited Jun 28, 2015 at 13:39 JimiLoe 9782 gold badges15 silver badges24 bronze badges asked Jun 14, 2013 at 3:00 user2435903user2435903 713 silver badges11 bronze badges 1-
use
keypress
eventmyInput.addEventListener('keypress', handler)
– Jonathan de M. Commented Jun 14, 2013 at 3:03
2 Answers
Reset to default 6onkeyup
is best suited for your task:
Type amount $: <input type='text' id='amount' onkeyup="updateConverted()" >
<br>
Converted: <input type='text' id='converted' >
JavaScript function:
function updateConverted() {
var conversionRate = 1.5;
document.getElementById('converted').value =
document.getElementById('amount').value * conversionRate;
}
Demo here.
Update (JSP for
loop):
In the case of your for
loop, you can just use the following jQuery code (no need to change the 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. If possible, avoid that as it is invalid HTML.
Simple using 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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745137389a4613268.html
评论列表(0条)