user2838698
user2838698

Reputation:

What's the error in following code snippet of jQuery?

$("#ckbCheckAll").click(function () {   

  $('div .bulkop .ez-checkbox').toggleClass("ez-checked", this.checked);

    var id_checkboxes = $('div .bulkop .ez-checkbox input').map(function() {
      return this.id;
    }).get();
   for (var i = 0; i < id_checkboxes.length; i++) {
   if (('#'+id_checkboxes[i]).is(':checked')) { 
        ('#'+id_checkboxes[i]).removeAttr('checked');
      }
      else{ //alert("In Else");
        ('#'+id_checkboxes[i]).attr('checked');
      }
 }
 });

I'm getting the following error in console:

TypeError: id_checkboxes[i].val is not a function
[Break On This Error]   

if (("#"+id_checkboxes[i].val()).is(':checked')) {

Upvotes: 0

Views: 74

Answers (3)

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

The problem here is that the method get() returns the native DOM elements collection, and not a jQuery object.

So, since it is not a jQuery object, it does not have the val() method.

Hence, the line

("#"+id_checkboxes[i].val()).is(':checked')

should actually be

$("#"+$(id_checkboxes[i]).val()).is(':checked') // added "$" in front

but I would replace the whole handler as

$("#ckbCheckAll").click(function () {
    $('div .bulkop .ez-checkbox')
        .toggleClass("ez-checked", this.checked)
        .find('input')
        .prop('checked', this.checked); //Toggle "checked" to the same state of #ckbCheckAll
});

JSFiddle: http://jsfiddle.net/Krh9S/2/

Upvotes: 2

h2ooooooo
h2ooooooo

Reputation: 39532

Why not just use $.each and .prop()?

$("#ckbCheckAll").click(function () {
    $('div .bulkop .ez-checkbox').toggleClass("ez-checked", this.checked);

    $('div .bulkop .ez-checkbox input').each(function() {
        $(this).prop('checked', !$(this).is(':checked')); //Toggle "checked"
    });
});

Upvotes: 3

Murali Murugesan
Murali Murugesan

Reputation: 22619

Wrap the $(string selector) with jQuery($)

Change

  ("#"+id_checkboxes[i].val())

to

 $("#"+id_checkboxes[i]).val() 

Then

('#'+id_checkboxes[i]).is(':checked') 

to

$('#'+id_checkboxes[i]).is(':checked')

NOTE:

You can't call val() like "#"+id_checkboxes[i].val(), since id_checkboxes[i] is string

Also you cant do $("#"+id_checkboxes[i].val()).is(':checked')

Upvotes: 0

Related Questions