user2064000
user2064000

Reputation:

JS - Cant check if checkbox is checked

I'm trying to write a web page with various options that can be enabled/disabled.

However, it seems that those options are always enabled, regardless of whether the relevant check boxes are selected or not.

Here's the code:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <script type="text/javascript">
            function check() {
                var options = "";
                if (document.form1.nocase.value) {
                    options = "1";
                }
                if (document.form1.ck2.value) {
                    options = options + "2";
                }
                alert (options);
            }
        </script>
        <form name="form1">
            <input type="checkbox" name="nocase">option 1
            <input type="checkbox" name="ck2">option 2
            <input type="button" value="Check" onclick="check();">
        </form>
        <div id="results"></div>
    </body>
</html>

I really am having problems understanding where the fault lies. Can anyone point it out?

Thanks in advance.

Upvotes: 0

Views: 63

Answers (1)

basilikum
basilikum

Reputation: 10528

You should use the checked property and not the value property of your input fields:

if (document.form1.nocase.checked) {
    //code here
}

The value attribute is string value that is sent to the server for every checked checkbox and you can specify its value in the html tag:

<input type="checkbox" name="nocase" value="nocase">

The checked property gives you the desired boolean that shows whether or not the checkbox is checked.

Upvotes: 3

Related Questions