jampjamp
jampjamp

Reputation: 31

Adding a class to checked input

I want to do sth like this: if one of inputs is defautly selected add the class to his table parent. I have original code which adds or removes the class to chosen input:

$('.table tr.table-selection').click(function() {
$('.table tr').removeClass('success').find('input').prop('checked', false); 
$(this).addClass('success').find('input').prop('checked', true); 
});

So, I tried to add similar code:

$('.table tr.table-selection').ready(function() {
$(this).addClass('success').find('input').prop('checked', true); 
});

But it doesn't work. I'm not well familiar with jQuery, what should I change?

Upvotes: 0

Views: 71

Answers (3)

Burak Güneli
Burak Güneli

Reputation: 124

if you want to check rather input defaultly comes checked or not, you don't need to write an .click(function(){})

you only need to write an if/else condition like this:

$(document).ready(function() {
    var checkControl = $('.table tr.table-selection');
    if(checkControl.find('input').prop('checked', true)){
       $(this).addClass('success');
    }else{
        $(this).addClass('fail');
    }
});

Upvotes: 0

Gerard
Gerard

Reputation: 15786

Use the following to run it on load:

$(document).ready(function() {
  $('.table tr.table-selection')
  .addClass('success').find('input').prop('checked', true); 
});

Upvotes: 1

Sebastien Napo
Sebastien Napo

Reputation: 61

Maybe use :

    $('.table tr.table-selection').on("click", function(){
          $(this).addClass('success').find('input').prop('checked', 
          true);
    })

[EDIT] If you want on load maybe just do this :

    $('.table tr.tableselection').addClass('success').find('input').prop('checked',true);})

Upvotes: 0

Related Questions