简体   繁体   中英

Copy value from one form field into another without checkbox

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>

FIDDLE

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>

EXAMPLE FIDDLE

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.

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