开发者

Calling checkbox only if checked

i have a checkbox that toggled with a button but i also need to add the its value to an equation, ONLY IF its checked. what i got right now is this, but it just add regardless of whether the checkbox is checked or not

<html>
<head>
<script language=javascript>
function validate(chk){
  if (chk.checked == 1)
    chk.checked = 0;
  else
    chk.checked = 1; 
}
</script>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
<form name="myform">
<input type="checkbox" name="ghj" id="ghj" value="100000">testing sheep<br>
<input type="button" class="button-primary widget-control-save" name="Check_All" value="Check All" onmouseout="compute(this.form)" onClick="validate(ghj)">
<input type="text" id="rslt" name="rslt">
</form>
<script type="text/javascript">
<!-- hide this script from old browsers
开发者_Python百科function compute(form)
{
var test = parseInt(document.getElementById('ghj').value, 10) || 0;
f = (test + 10);

document.getElementById('rslt').value = f;
}

// done hiding from old browsers -->
</script>
</body>
</html>

if...else statements may work but if i have a longer form that would mean hundreds of possibilities, and i'd like a more efficient way..


If you want to compute only the checkbox which are checked. Then do something like this

function compute(frm){
    var test = 0;
    for(var i = 0; i < frm.elements.length; i++){
        if(frm.elements[i].type == 'checkbox'){
            if(frm.elements[i].checked){ //Do something if checkbox is checked
                test += parseInt(frm.elements[i].value);
            }
        }
    }
    document.getElementById('rslt').value = test;

}

See sample code jsfiddle.net/5u5TH


It took me a little while to figure out what you're asking but I think you want to do something like this:

function compute(form)
{
  var checkbox = document.getElementById('ghj');
  if(checkbox.checked) {
    var test = parseInt(checkbox.value, 10) || 0;
    f = (test + 10);
    document.getElementById('rslt').value = f;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜