Jump to content

[SOLVED] Forms and JS


ManifestX

Recommended Posts

Hello there. I'm new, and I have some questions on creating a variable, which takes a value, "quantity", and whatever number you input, multiplies them, then outputs it to "amountNum". I've used onChange, but there is no value displayed in that field. I don't know what it is that's wrong with my code and was hoping you could help.

 

Here's my code so far:

 

...
      <SCRIPT language=Javascript>
      <!--
      function getAmount(quantity, num)
      {
         return quantity*num;
      }
      //-->
      </SCRIPT>
...
<td> <INPUT align="right" id="txtChar" onkeypress="return isNumberKey(event)" type="text" maxlength="3" size="1" name="quantity" value="0">  </td>
<td>x$2.50</td>
<td> <INPUT align="right" id="amntChng" onchange="this.quantity.getAmount(this.quantity.value, 2.50)" type="text" maxlength="6" size="1" name="amountNum" disabled="disabled">  </td>
...

Link to comment
https://forums.phpfreaks.com/topic/170420-solved-forms-and-js/
Share on other sites

JavaScript is a bit different than other languages.  Returning a value doesn't stick it in an element.  Also, the way you're attempting to use events is a bit weird.  You simply need:

 

<script type="text/javascript">
   window.onload = function(){
      var quantity = document.getElementById('txtChar');
      var amount = document.getElementById('amntChng');

      quantity.onchange = function(){
         amount.value = this.value * 2.50;  //you may need amount.innerHTML = this.value * 2.50 instead
      }
   }
</script>

...

<td><input id="txtChar" /></td>
<td><input id="amntChng" /></td>

 

A couple of key ideas here:

 

I don't like mixing JS and HTML.  It's a style choice, but in my experience, things are easier to fix/manage/edit/maintain if markup and script are separate.  So, my solution does away with inline JS calls in the HTML.  To put it another way, you wouldn't need to add events (i.e., onchange) to the elements themselves within the HTML.

 

The code isn't necessarily complete.  It should show you how to approach the problem, however.

Link to comment
https://forums.phpfreaks.com/topic/170420-solved-forms-and-js/#findComment-899051
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.