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

Community
  • 1
  • 1
quba88
  • 174
  • 4
  • 18
  • Can you post the HTML that contains the checkboxes? – Grim... Feb 21 '12 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. – Anthony Grist Feb 21 '12 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? – Surreal Dreams Feb 21 '12 at 16:56

1 Answers1

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'>
Dennis
  • 14,264
  • 2
  • 48
  • 57
  • 1
    Replace `'checked'` with `true`. You are accessing the boolean property, not the string attribute. – ThiefMaster Feb 21 '12 at 17:10
  • 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. – quba88 Feb 21 '12 at 21:41