mpavlovic89
mpavlovic89

Reputation: 769

JavaScript checkbox onclick function

I am stuck at the simple JavaScript function, related to the checkbox validation. I need to document.write if the cb1 is checked, and the same if cb2. And if both, or one of them isn't checked, then write nothing.

<html>
<head>
<title>TEST PAGE</title>
    <script type="text/javascript" src="submit.js"></script>
</head>
<body>
    <div style="width:100%"><input type="checkbox" id="cb1"></div>
    <div style="width:100%"><input type="checkbox" id="cb2"></div>

    <div style="width:100%"><input type="submit" name="execute" id="execute" value="Execute" onClick="run();"></div>

</body>
</html>

submit.js

function run() {

    document.write('<div>' + "HERE GOES YOUR CHECKBOX CHOICE: " + '</div>');

    if(document.getElementById("cb1").checked == true) {
        document.write("This is check box 1");
    }
    if(document.getElementById("cb2").checked == true) {
        document.write("This is check box 2");
    }
}

Upvotes: 1

Views: 10831

Answers (4)

audiochick
audiochick

Reputation: 184

Here is an improved run function:

function run() {

    var snip = "<div>HERE GOES YOUR CHECKBOX CHOICE: </div>";

    if(document.getElementById("cb1").checked == true) {
        snip += "<br/>This is check box 1";
    }
    if(document.getElementById("cb2").checked == true) {
        snip += "This is check box 2";
    }
    document.write(snip);
}

Everyone spotted the error of overwriting you html before actually reading the elements, so that was the cause of your error, clearing the DOM and then trying to read an input property that no longer exists.

Upvotes: 2

Bic
Bic

Reputation: 3134

if (document.getElementById('cb1').checked && document.getElementById('cb2').checked) {
    // both are checked
}
else {
   // only one or none are checked
}

As was mentioned in one of the previous answers, you should not use document.write. You can use .append(string) to add things to the document:

document.append('Both boxes are checked');

Upvotes: 0

shyamnathan
shyamnathan

Reputation: 133

just use .checked in javascript in jquery use .prop('checked')

function run() {    

if(document.getElementById("cb1").checked) {
    document.write("<div>This is check box 1</div>");
}
if(document.getElementById("cb2").checked) {
    document.write("<div>This is check box 2</div>");
}
}

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

you shouldnt use document.write. use append to tags like

$("#divid").append($("<input/>",{type:"checkbox",onclick:"yourfunction(this)"}));

Upvotes: 1

Related Questions