0
  <script src="Multiply_form_2.js"></script>

<form>
<ul>
    
        <li><label>First Value: <input type="text" name="nFirst" onblur="multiply.call(this,this.form.elements.mFirst.value,this.form.elements.mFirst.value)"></label></li>
          
</form>





function multiply(one, one) {
  if(one && one){
    this.form.elements.mFirst.value = one * one;
  } else {
    this.style.color='red';
  }
}

Hello I have some code and I want to be able to multiply two numbers in one box. Something like 6 * 2 and then it will make it 12 when you click away (like how it is now) If there are any resources you can point me towards I would appreciate it. Trying to multiply in the same box as shown above.

1 Answers1

0

The first thing would be not to set up your event handlers inline with your HTML. That's a 25+ year old technique that will not die because people just keep copying from someone else. There are real reasons not to use it and instead use the modern .addEventListener() API.

Next, form fields have a value property which is how you access the data within them. Your code attempts to multiply the actual input elements.

I hope this is really just an exercise in learning and not a real implementation because this doesn't make for a very efficient user interface and present validation challenges, but what you'll need to do is split the input string where the asterisk is and multiply the two resulting parts.

There are still other things to add, but read the comments in the code below for more details.

// Get a reference to the second input and set up a blur event handler on it
document.querySelector("input[name='mFirst']").addEventListener("blur", multiply);

function multiply() {
  // Since this function is bound to the second input, you can reference
  // it with the "this" keyword. But when you reference a form field
  // you must get its value property to get what's in it
  if(this.value){
    // Split the value at the asterisk, which will put the 
    // operands into an array
    let nums = this.value.split("*");
    this.value = nums[0] * nums[1];
  } else {
    // Avoid inline styles. Add or remove pre-made classes instead
    this.classList.add("invalid");
  }
}
.invalid { border:1px dotted red; }
<form>
  <ul>
    <li><label>First Value: <input type="text" name="mFirst"></label></li>
  </ul>
</form>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71