Reputation: 13
i want to add 500 using onclick function in span 1000 means onclick at check box sapn value will be 1500
JS
function add() {
if (document.Form1.checkbox1.checked == true) {
// what will code here to sum 500 in to 1000
}
}
HTML
<form name="Form1" style="color: green ; font-size: 150%" action="#">
<input type="checkbox" name="checkbox1" onclick="add()" />500
<br />
<span>1000</span>
</form>
Upvotes: 0
Views: 14009
Reputation: 15846
If you don't want to use jQuery, then the the following can be used.
function add(element) {
var form = document.getElementsByName("Form1")[0];
var val = form.getElementsByTagName('span')[0].innerHTML;
if (element.checked == true) {
form.getElementsByTagName('span')[0].innerHTML = parseInt(val) + parseInt(element.value);
} else {
form.getElementsByTagName('span')[0].innerHTML = parseInt(val) - parseInt(element.value);
}
}
<form name="Form1" style="color: green ; font-size: 150%" action="#">
<input type="checkbox" name="checkbox1" onclick="add(this)" value="500" />500
<br />
<span>1000</span>
</form>
Upvotes: 1
Reputation: 1175
Please try the bellow code,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#checkbox1').click(function(){
var checkboxval = parseInt($(this).val());
var spanval = parseInt($('#total').text());
if(this.checked){
$('#total').text(checkboxval + spanval);
}
});
});
</script>
<body>
<form name="Form1" style="color: green ; font-size: 150%" action = "#">
<input type="checkbox" name="checkbox1" id="checkbox1" value="500"/>500
<br/>
<span id="total">1000</span>
</form>
</body>
Let me know if you have any query
Thanks
Upvotes: 0
Reputation: 726
<span id="myspan"> 1000 </span>
try this code -
document.getElementById("myspan").innerHTML="1500";
for modern browser-
document.getElementById("myspan").textContent="1500";
Upvotes: 0
Reputation: 597
As Kushal has mentioned in their four comments, you need to add an identifying feature to the span so you know where to put the new value.
You can then use document.getElementById()
(if in javaScript) or $('#id')
(in jQuery) to access this element and change the text (via innerText/innerHTML in js and .text()/.html() in jQuery)
Upvotes: 0
Reputation: 101
Make sure to add an id to your span element so you can easily target it in javascript. Then target the element and change the innerHTML.
var spanToChance = document.getElementById("#spanID");
spanToChange.innerHTML = parseInt(spanToChange.innerHTML) + 500;
Upvotes: 3
Reputation: 25527
Example code
$("[name='checkbox1']").change(function () {
var spanvalue = parseInt($("span").text().trim());
if (this.checked) {
spanvalue = spanvalue + parseInt(this.value);
} else {
spanvalue = spanvalue - parseInt(this.value);
}
$("span").text(spanvalue);
});
Upvotes: 0