0

I have a function for select/check all checkbox that id=hap

$(function () {
       $('#select-all').click(function (event) {

           var selected = this.checked;
           
           $('#hap').each(function () {    this.checked = selected; });

       });
    }); 

This is my checkbox to select all.

<input type='checkbox' id='select-all'><label for='select-all'>Delete all</label>

And I use it for select data that I've fetched by php

$data=mysql_query("SELECT*FROM comment where news_id='$id'");
    $x=0;
    while($a=mysql_fetch_array($data)){
                                        
    $x++;
    echo"

<td class='center'>
    <input id='hap' type='checkbox' name='c_$x' value='$a[comment_id]'>
</td>";

}

But it just select/check one data in the first loop, another data isn't selected.

Anyone know what's wrong with it?

1
  • 2
    Please use PDO or MySQLi instead of the old mysql_* functions, because it's depreciated. Commented Jan 8, 2014 at 15:39

4 Answers 4

3

ID's are unique. If you have more than one ID on a page it will only use the first. If you need more than one of something on a page you need to use Class instead.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this code. Change id to class

 echo"

<td class='center'>
    <input class='hap' type='checkbox' name='c_$x' value='$a[comment_id]'>
</td>";

In js

$(function () {
       $('#select-all').click(function (event) {

           if($(this).is(':checked')) {
        $(".hap").attr('checked', 'checked');
    } else {
        $(".hap").removeAttr('checked');
    }


}); 

1 Comment

may you consider to use .prop() instead .attr() (if jq version is 1.6+) api.jquery.com/prop
0

Try this:

function actualizarSeleccion(){
   $('.hap').each(function () {    
       this.checked = document.getElementById("select-all").checked;; 
   });
}    

<input type='checkbox' id='select-all' onchange="actualizarSeleccion()"><label for='select-all'>Delete all</label>

Comments

0

Maybe you like this way:

$(function () {
     $('#select-all').click(function() {
          $(".hap").prop("checked", this.checked);
     });
});
  • without set a useless variables
  • without use each method (instead use prop in jquery collection of object)

Comments

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.