0

i want to disable all elements of my class where my checkbox is not checked. But even this is checked, my if returns false.

$('.myClass').each(function(i, obj) {
  if (!$j('input[name='+obj.id+']').is(':checked')){  
    $j('#desc_'+obj.id).attr('disabled','disabled');              
  }        
});

But if i put a alert inside the if, its works!

$('.myClass').each(function(i, obj) {
  if (!$j('input[name='+obj.id+']').is(':checked')){  
    alert($j('input[name='+obj.id+']').is(':checked'));
    $j('#desc_'+obj.id).attr('disabled','disabled');              
  }        
});

Anyone knows why?

4

3 回答 3

5

Developers tend to use console.log instead, alert() behaves differently because the DOM wont load in full until AFTER the "OK" button has been clicked on the alert.

Consider using:

$('.myClass').each(function(i, obj) {
      if (!$j('input[name='+obj.id+']').is(':checked')){  
        console.log($j('input[name='+obj.id+']').is(':checked'));
        $j('#desc_'+obj.id).prop('disabled','disabled');              
      }        
    });

For more information and documentation see:

What is console.log and how do I use it?

and

https://developer.mozilla.org/en-US/docs/Web/API/console.log

EDIT:

I would also consider using .prop over .attr, the main differences and reasons for this are highlighted here:

.prop() vs .attr()

There's no point in me re-inventing the wheel!

于 2013-09-10T14:53:39.807 回答
0

Looks like you were referencing jQuery wrong. Try this :

$('.myClass').each(function(i, obj) {
    if (!$('input[name='+obj.id+']').is(':checked')){  
        $('#desc_'+obj.id).attr('disabled','disabled');              
    }        
});

The difference is ..$j(.. vs ..$(..

于 2013-09-10T15:00:25.667 回答
-1

Ensure that you're code is wrapped in the $(function() { ... }

$(function() {
  $('.myClass').each(function(i, obj) {
    if (!$j('input[name='+obj.id+']').is(':checked')){  
      $j('#desc_'+obj.id).attr('disabled','disabled');              
    }        
  });
});
于 2013-09-10T14:55:47.297 回答