我根据4个文本框的值进行一些计算,但我只想在4个文本框有值时才计算这个值。
听起来很简单,但我想不出一种只在以上条件为真并在每个键上重新计算的情况下运行calc的方法。
$(window).load(function(){
$('#quantity, #length, #width, #height, #weight').keyup(function () {
$('#volumetric_weight').val($('#length').val()*$('#width').val()*$('#height').val()*$('#quantity').val()/5000);发布于 2016-01-10 20:05:46
尝试使用required属性,仅在每个input有效时计算
$(function() {
var inputs = $("form input"), product = 1;
inputs.on("input", function() {
if (document.forms["calculate"].checkValidity()) {
inputs.each(function(i, el) {
product *= el.value;
});
$("#volumetric_weight").val(product / 5000);
product = 1;
}
})
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form name="calculate">
<input type="number" id="quantity" required />
<input type="number" id="length" required />
<input type="number" id="width" required />
<input type="number" id="height" required />
<input type="number" id="weight" required />
</form>
<input type="text" value="" id="volumetric_weight" />
jsfiddle https://jsfiddle.net/b185Lh80/
发布于 2016-01-10 20:07:55
您需要首先检查输入字段是否有值(所有这些值),然后执行您的代码。在您的问题中,您提到了4个文本框,但在您的代码中有5 ;)类似于
$(window).load(function(){
$('#quantity, #length, #width, #height, #weight').keyup(function () {
if(!$('#quantity').val() || !$('#length').val() || !$('#width').val() || !$('#height').val() || !$('#weight').val()) return;
$('#volumetric_weight').val($('#length').val()*$('#width').val()*$('#height').val()*$('#quantity').val()/5000);发布于 2016-01-10 20:16:00
在计算之前,您可以简单地测试所有值是否都存在:
$(window).load(function(){
$('#quantity, #length, #width, #height, #weight').change(function () {
var len = $('#length').val();
width = $('#width').val();
height = $('#height').val();
qty = $('#quantity').val();
if (&& width && && qty) {
$('#volumetric_weight').val(len * width * height * qty / 5000);
}
});
})请注意,我使用了@Mathew:将change()替换为keyup()的建议,以便在用户过去时捕获。
https://stackoverflow.com/questions/34710200
复制相似问题