quba88
quba88

Reputation: 174

JavaScript & PHP checkbox select all

I have problem with select checkbox with the JavaScript in the HTML file. I know how to do this but in my form all checkbox have name='chk[]':

<form name="forms" action='index.php' method='post'>
    <input type='checkbox' name='chk[]' value='value1'> ANY VALUE 1 </br>
    <input type='checkbox' name='chk[]' value='value2'> ANY VALUE 2 </br>
    <input type='checkbox' name='chk[]' value='value3'> ANY VALUE 3 </br>
    <input type='checkbox' name='chk[]' value='value4'> ANY VALUE 4 </br>
    <input type='submit' name='submit' value='Get Value'>
</form>

In my PHP file I use select checkbox:

<?php
    $s = "";
    $value = $_POST['chk'];

    $s .= join(", ", $value);

    echo $s;

But how can I create a function in JavaScript which checks the field. I've also tried this

Upvotes: 0

Views: 8066

Answers (1)

Dennis
Dennis

Reputation: 14477

To check all checkboxes dynamically, you can use the follwing code:

var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++)
    if(inputs[i].type == "checkbox")
        inputs[i].checked = true;

To check a checkbox by default, just add checked='checked' to the tag:

<input type='checkbox' name='chk[]' value='value' checked='checked'>

Upvotes: 2

Related Questions