I've got two inputs in a div that I want to divide one by the other.
<div>
<input type="number" id="a"> / <input type="number" id="b">
<input type="submit">
<p class="result">RESULT HERE</p>
</div>
How can the maths of this be done with jquery?
I've got two inputs in a div that I want to divide one by the other.
<div>
<input type="number" id="a"> / <input type="number" id="b">
<input type="submit">
<p class="result">RESULT HERE</p>
</div>
How can the maths of this be done with jquery?
Share Improve this question edited Oct 17, 2011 at 21:01 Stuart Robson asked Oct 17, 2011 at 20:52 Stuart RobsonStuart Robson 1,1494 gold badges22 silver badges43 bronze badges 3 |2 Answers
Reset to default 15It really depends when you want the calculation to take place, but the maths itself is incredibly simple. Just use the standard division operator, /
:
var num1 = $("input[label='a']").val(),
num2 = $("input[label='b']").val(),
result = parseInt(num1, 10) / parseInt(num2, 10);
$(".result").text(result);
I guess it also depends if you only want to support integer division (that's why I've used parseInt
- you could use parseFloat
if necessary).
Also, as mentioned in the comments on your question, label
is not a valid attribute. A better option would be to use id
, or if you need to use an arbitrarily named attribute, use HTML5 data-*
attributes.
Update based on comments
As you have stated that you want the code to run when a button is clicked, all you need to do is bind to the click
event:
$("#someButton").click(function() {
//Do stuff when the button is clicked.
});
You're mixing your markup with your logic. You can't divide HTML elements with each other they are for structural presentation only. Instead, you have to pull their values with javascript, apply the math, and update the HTML with the resulting value.
label
attribute? – millimoose Commented Oct 17, 2011 at 20:55label
isn't a real attribute. I think you meanid
orname
. – Brian Nickel Commented Oct 17, 2011 at 20:58