JQuery only gets checkbox value when validated

Right now, I'm using the following bit of code to get only the values โ€‹โ€‹of checked flags, however I'm sure there is an easier way to do 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-scuba-diver = $('#OPTtags-master-scuba-diver').val() } else var OPTtags-master-scuba-diver = ''; 

Whether there is a?

Wonderful

+7
source share
5 answers

I have not tested this, but what about

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

Then your variable will be undefined or value.

+8
source

This is a little easier:

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

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

+3
source

Another way:

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

try it,

 var OPTtags-master-scuba-diver = $('#OPTtags-adventure-diving:checked').val() || '': 
0
source
 $('#OPTtags-adventure-diving').prop('checked') ? $('#OPTtags-adventure-diving').val() : '' 
-one
source

All Articles