Reputation: 16577
I have a form with three items with checkboxes and prices. In a paragraph underneath I have an area for the total price, and an area for the items selected. How can I update these two areas when each checkbox is checked?
<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>
How can I achieve this with jQuery or JavaScript? I don't really want to use a textbox for putting the values in, I'd rather they were in-line text. So I want the object names in the first bit, and the total price in the second.
Upvotes: 1
Views: 859
Reputation: 65264
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>
demo
Upvotes: 3
Reputation: 5405
I have used jquery for acheiving your requirement.
Try this -
<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');
}
});
});
Upvotes: 2
Reputation: 6999
Using pure JS (untested)
handleCheckbox = function(){
if(this.checked) {
document.getElementByTagName("span")[0].innerText = this.attributes["name"].value;
document.getElementByTagName("span")[1].innerText = this.value;
}
}
However, there should be radio instead of checkbox. Add onClick="handleCheckbox"
on checkbox
Upvotes: 1