单击复选框时如何更改某些文本?
我有一个带有复选框和价格的三个项目的表单。在下面的段落中,我有一个总价格区域,以及所选项目的区域。如何在每个复选框被选中时更新这两个区域?单击复选框时如何更改某些文本?
<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
我已经使用jquery来达到您的要求。
试试这个 -
<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 id="name">name of items here</span>, it will cost you a total of £<span id="price">price here</span>.
<input type="submit"/>
</form>
$(document).ready(function(){
$('input[type="chechbox"]').click(function()[
if($(this).is(':checked')){
$('#price').html($(this).val());
$('#name').html($(this).attr('name'));
}else{
$('#price').html('Price');
$('#name').html('name');
}
});
});
.val()是否适用于跨度?还是需要.html()? – StuperUser 2011-01-13 08:46:44
@StuperUser:感谢它不会,因此更新我的代码。 – Alpesh 2011-01-13 08:48:19
使用纯JS(未经测试)
handleCheckbox = function(){
if(this.checked) {
document.getElementByTagName("span")[0].innerText = this.attributes["name"].value;
document.getElementByTagName("span")[1].innerText = this.value;
}
}
但是,应该有无线电,而不是复选框。上复选框添加onClick="handleCheckbox"
您将要重新计算服务器上的成本太高,万一有人伪造POST的值较低。减值曾经导致应用程序用订单付款。 – StuperUser 2011-01-13 12:37:35
是的,我明白你的观点。这个价格虽然只是一个标签,但实际产品的价格是服务器端计算得出的。不过谢谢。 – edwardmlyte 2011-01-13 15:02:56