ManifestX Posted August 15, 2009 Share Posted August 15, 2009 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> ... Quote Link to comment https://forums.phpfreaks.com/topic/170420-solved-forms-and-js/ Share on other sites More sharing options...
KevinM1 Posted August 15, 2009 Share Posted August 15, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/170420-solved-forms-and-js/#findComment-899051 Share on other sites More sharing options...
ManifestX Posted August 17, 2009 Author Share Posted August 17, 2009 Thank you Nightslyr, I was able to finish it with your help. Cheers! Quote Link to comment https://forums.phpfreaks.com/topic/170420-solved-forms-and-js/#findComment-899830 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.