0

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?

3
  • 1
    What's the label attribute? Commented Oct 17, 2011 at 20:55
  • label isn't a real attribute. I think you mean id or name. Commented Oct 17, 2011 at 20:58
  • 1
    The math can't be done with jQuery. You have to use simple JavaScript. I suggest you read this: developer.mozilla.org/en/JavaScript/Guide Commented Oct 17, 2011 at 21:18

2 Answers 2

15

It 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.
});
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for this :) I'd want the user to be able to enter the two figures then click a submit button that'd then show the answer (on the same page if possible). I guess I need to add a submit button to my HTML ? :)
Yeah that's right, and you'd need to bind a click event handler to that element. See my edit.
/ will automatically coerce into a number, so you could simply do num1 / num2.
@pimvdb - Yeah true, but I just wanted to make it clear what's actually going on, instead of letting the JS engine take care of it :)
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.