1

I have a page that has a number of checkboxes in it. I would like to write a function that will be called when the ckeckbox is clicked, that determines if the checkbox is checked or not.

<input type="checkbox" onclick="toggleVis('id',   this);"/> ID
<input type="checkbox" onclick="toggleVis('edit', this);" checked="checked"/> Edit
<input type="checkbox" onclick="toggleVis('last', this);"/> Last

Note some checkboxes start checked.

I figured that there must be a way to do this based on a reference passed, so I passed the this value as a parameter.

function toggleVis(name, checkbox)
{
    //if(checkbox.checked())
        console.log('checked');

        if($('.'+name).css('display') != "none")
            $('.'+name).css('display', 'none');
        else
             $('.'+name).css('display', 'table-cell');
}

I am open to use jQuery.

1
  • Did your code work? If not what happened? Get Firebug and see what the objects passed actually are. Commented Dec 15, 2010 at 14:35

5 Answers 5

1

You were close.

if(checkbox.checked) {
    console.log('checked');
    //...
}

There's no checked() method, but there is a checked property. Note that your code may only work on clicks. Perhaps onchange would be better?

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

Comments

1

Look at the checkboxobj.checked property (instead of calling it like a function). In your case, you could reference if (checkbox.checked) { ... }. More information can be found on this website

Comments

1

If you wanted to do this with jQuery you might try the following. Note that I'm binding to the checkbox instead of including the 'onclick' or 'onchange' directly on the HTML element.

$('[type=checkbox]').click(function(){
  if( $(this).attr('checked') ){
    console.log('checked');
    if($('.'+$(this).attr('name')).css('display') != "none") {
      $('.'+$(this).attr('name')).css('display', 'none');
    } else {
      $('.'+$(this).attr('name')).css('display', 'table-cell');
    }
  }
});

Comments

0

And a JQuery-based solution:

var checked = $(checkbox).is(':checked');

Helpful if you want to find the checkbox first by some JQ selector.

Comments

0
<input type="checkbox" class="checkthis"> ID
<input type="checkbox" class="checkthis" checked="checked"> Edit
<input type="checkbox" class="checkthis"> Last

$(input.checkthis).click(function() {
  if($(this).is(':checked') {
    // do checked stuuf
  } else {
    // do not checked stuff
  }
});

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.