Simple Maths with jQuery - division

白昼怎懂夜的黑 提交于 2019-12-11 18:08:50

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/7799438/simple-maths-with-jquery-division

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!