5

我试图根据复选框的状态更改变量的值这是我的代码示例

<script type="text/javascript">
if(document.getElementByType('checkbox').checked)
{
var a="checked";}
else{
var a="not checked";}
document.getElementById('result').innerHTML ='result '+a;
</script>
<input type="checkbox" value="1"/>Checkbox<br/>
<br/>
<span id="result"></span>

你能告诉我这段代码有什么问题吗?

4

6 回答 6

7

Try this:

if (document.querySelector('input[type=checkbox]').checked) {

Demo here

Code suggestion:

<input type="checkbox" />Checkbox<br/>
<span id="result"></span>
<script type="text/javascript">
window.onload = function () {
    var input = document.querySelector('input[type=checkbox]');

    function check() {
        var a = input.checked ? "checked" : "not checked";
        document.getElementById('result').innerHTML = 'result ' + a;
    }
    input.onchange = check;
    check();
}
</script>

In your post you have the javascript before the HTML, in this case the HTML should be first so the javascript can "find it". OR use, like in my example a window.onload function, to run the code after the page loaded.

于 2013-10-16T12:41:13.663 回答
3
            $('#myForm').on('change', 'input[type=checkbox]', function() {
                this.checked ? this.value = 'apple' : this.value = 'pineapple';
            });
于 2014-12-17T12:14:31.810 回答
0

尝试这样的事情

<script type="text/javascript">
    function update_value(chk_bx){
        if(chk_bx.checked)
        {
            var a="checked";}
        else{
            var a="not checked";
        }
        document.getElementById('result').innerHTML ='result '+a;

    }

</script>
<input type="checkbox" value="1" onchange="update_value(this);"/>Checkbox<br/>
    <span id="result"></span>
于 2013-10-16T12:42:41.293 回答
0

对于那些尝试了以前的选项并且由于任何原因仍然有问题的人,您可以使用 .prop() jquery 函数这样:

$(document.body).on('change','input[type=checkbox]',function(){
    if ($(this).prop('checked') == 1){
        alert('checked');
    }else{
        alert('unchecked');
}
于 2016-03-12T08:36:59.453 回答
0

太复杂。内联代码让它很酷。

<input type="checkbox" onclick="yourBooleanVariable=!yourBooleanVariable;">
于 2016-01-14T20:07:39.823 回答
-1

This code will run only once and check initial checkbox state. You have to add event listener for onchange event.

window.onload = function() {
    document.getElementByType('checkbox').onchange = function() {
        if(document.getElementByType('checkbox').checked) {
            var a="checked";
        } else {
            var a="not checked";
        }
        document.getElementById('result').innerHTML ='result '+a;
    }
}
于 2013-10-16T12:41:28.007 回答