开发者

JQuery get value of checkbox only if checked

At the moment I am using the following bit of code to only get the values of checked checkboxes, however I am sure that there is an easier way that this.

if ($('#OPTtags-adventure-diving').is(':checked')) {
        var OPTtags-adventure-diving = $('#OPTtags-adventure-diving').val()
    } else var OPTtags-adventure-diving = '';

    if ($('#OPTtags-master-scuba-diver').is(':checked')) {
        var OPTtags-master-scu开发者_如何学Goba-diver = $('#OPTtags-master-scuba-diver').val()
    } else var OPTtags-master-scuba-diver = '';

Is there?

Marvellous,


I have not checked this, but how about

var OPTtags-master-scuba-diver = $('#OPTtags-adventure-diving:checked').val()

Then your variable will be undefined or the value.


This is a bit simpler:

var OPTtags-adventure-diving = $('#OPTtags-adventure-diving:checked').length ? $('#OPTtags-adventure-diving').val() : '';

Example - http://jsfiddle.net/infernalbadger/SfcjG/


Just another way:

var $chkbox = $('#OPTtags-adventure-diving'),
    OPTtags-adventure-diving = $chkbox.is(':checked') ? $chkbox.val() : '';


try this,

var OPTtags-master-scuba-diver = $('#OPTtags-adventure-diving:checked').val() || '':


$('#OPTtags-adventure-diving').prop('checked') ? $('#OPTtags-adventure-diving').val() : ''
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜