我有一个复选框,但将值分配给项目的名称。现在我有了这个隐藏字段,该字段具有分配给项目价格的值。现在,当我使用隐藏字段运行 jQuery 来计算所选项目的总和时,它不起作用。当我将价格和计算 ID 分配给复选框而不是隐藏字段时,它的工作方式正好相反。
这是我的jquery:
<script type="text/javascript">
function calcscore(){
var score = 0;
$(".calc:checked").each(function(){
score+=parseInt($(this).val(),10);
});
$('#price').text(score.toFixed(2));
$("input[name=sum]").val(score)
}
$().ready(function(){
$(".calc").change(function(){
calcscore()
});
});
</script>
和我的html:
<li>
<label>
<input class="calc" type="checkbox" name="seasoning[]" value="Title1"/>
The Title
</label>
<input type="hidden" name="title8" value="250">
</li>
<li>
<label>
<input class="calc" type="checkbox" name="seasoning[]" value="Title1"/>The Title
</label>
<input type="hidden" name="title8" value="150">
</li>
<p>Total: PHP <span id="price">0</span></p>
任何见解将不胜感激。谢谢
你的代码应该更像下面的解决方案,并检查它在jsfiddle上是如何工作的: https://jsfiddle.net/yehiaawad/wwtwmaLv/您的网页:
<li>
<label>
<input class="calc" type="checkbox" name="seasoning[]" value="Title1"/>
The Title
<input type="hidden" name="title8" value="250">
</label>
</li>
<li>
<label>
<input class="calc" type="checkbox" name="seasoning[]" value="Title1"/>The Title
<input type="hidden" name="title8" value="150">
</label>
</li>
<p>Total: PHP <span id="price">0</span></p>
您的 JS
function calcscore(){
var score = 0;
var checked=$(".calc:checked ~ input[type=hidden]").each(function(){
score+=parseInt($(this).val());
});
$('#price').text(score.toFixed(2));
}
$(document).ready(function(){
$(".calc").change(function(){
calcscore()
});
});