0

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

3
  • Can you post the HTML that contains the checkboxes? Commented Feb 21, 2012 at 16:50
  • 2
    Include the HTML for the checkboxes that is generated by your PHP code in the question, as well as the Javascript code you've tried that doesn't work, please. Commented Feb 21, 2012 at 16:51
  • So you want a script that checks all the checkboxes? Would it make sense to do this when the form is rendered, or is this a convenience button for the user to one-click and check all the boxes? Commented Feb 21, 2012 at 16:56

1 Answer 1

2

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'>
Sign up to request clarification or add additional context in comments.

2 Comments

Replace 'checked' with true. You are accessing the boolean property, not the string attribute.
Ok thx it's work fine now. I must create dynamic check, uncheck checbox in site generate by php. I don't know hove much was checkbox, and I need take it value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.