最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Simple Maths with jQuery - division - Stack Overflow

programmeradmin1浏览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?

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
  • 1 What's the label attribute? – millimoose Commented Oct 17, 2011 at 20:55
  • label isn't a real attribute. I think you mean id or name. – Brian Nickel 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 – Felix Kling Commented Oct 17, 2011 at 21:18
Add a comment  | 

2 Answers 2

Reset to default 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.
});

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.

发布评论

评论列表(0)

  1. 暂无评论