gpt4 book ai didi

javascript - 单击复选框时如何更改某些文本?

转载 作者:行者123 更新时间:2023-11-30 08:15:33 24 4
gpt4 key购买 nike

我有一个表单,其中包含三个带有复选框和价格的项目。在下面的段落中,我有一个总价区域和所选项目的区域。选中每个复选框后如何更新这两个区域?

<form>
<input type="checkbox" name="milk" id="checkbox" value="10.00"/>£10.00<br/>
<input type="checkbox" name="eggs" id="checkbox2" value="20.00"/>£20.00<br/>
<input type="checkbox" name="cheese" id="checkbox3" value="30.00"/>£30.00<br/>
If you buy <span>name of items here</span>, it will cost you a total of £<span>price here</span>.
<input type="submit"/>
</form>

如何使用 jQuery 或 JavaScript 实现此目的?我真的不想使用文本框来放入值,我宁愿它们是内联文本。所以我希望第一位是对象名称,第二位是总价。

最佳答案

jQuery

$(':checkbox').change(function() {
var sum = 0;
var names = $('form :checked').map(function(){
sum += (this.value - 0);
return this.name;
}).get().join(',');

var spans = $('form span');
spans[0].innerHTML = names;
spans[1].innerHTML = sum;
});

html

<form>
<input type="checkbox" name="milk" id="checkbox" value="10.00"/>£10.00<br/>
<input type="checkbox" name="eggs" id="checkbox2" value="20.00"/>£20.00<br/>
<input type="checkbox" name="cheese" id="checkbox3" value="30.00"/>£30.00<br/>
If you buy <span>name of items here</span>, it will cost you a total of £<span>price here</span>.
<input type="submit"/>
</form>

演示

simple demo

关于javascript - 单击复选框时如何更改某些文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4678101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com