开发者

Given a checkbox object output its value

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 toggleVi开发者_Go百科s(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.


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?


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


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');
    }
  }
});


And a JQuery-based solution:

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

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


<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
  }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜