I'd like to enter a number into a form field and have the field next to it automatically update to be 2x the number. I can't figure out how to do this without something like a checkbox.
I have this:
var val = document.form1.field1.value
if (/^\s*$/.test(val)) {
}
else {
document.form1.field2.value = val * 2
}
What I thought this would do is check if field1 has any value (otherwise I'd just like the fields to show placeholder), and if it does have a value it would make field2 = field1 * 2
My goal is to have field2 update as I type the numbers in field1.
Thank you for your help!
Add a keyup handler, and parse the value as a number (it's always a string) and multiply by 2 :
<form id="form1">
<input id="field1" onkeyup="fn(this)" />
<input id="field2" />
</form>
<script type="text/javascript">
function fn(elem) {
var val = parseFloat(elem.value) * 2 || '';
document.getElementById('field2').value = val;
}
</script>
Onchange or onkeyup, depending if you are looking for more than one digit.
<form name="form1">
<input name="field1"type="text" value="" onchange="fieldChanged(this)"/>
<input name="field2"type="text" value=""/>
</form>
<script type="text/javascript">
function fieldChanged(sender){
if (parseInt(sender.value) != NaN){
document.form1.field2.value = parseInt(sender.value) * 2;
{
else {
alert("Only numbers go there!");
}
}
</script>
Very simply. if(document.form1.field1.value!=''){ document.form1.field2.value=document.form1.field1.value; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.