7

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-scuba-diver = $('#OPTtags-master-scuba-diver').val()
    } else var OPTtags-master-scuba-diver = '';

Is there?

Marvellous,

2
  • 2
    Minor point: variable names with hypens are illegal in JS. The problem is that OPTtags-adventure-diving could be interpreted as OPTtags minus adventure minus diving. Better to use camelCase or underscore. Commented Mar 11, 2011 at 11:07
  • @johnhunter Point taken, Commented Mar 11, 2011 at 18:58

5 Answers 5

9

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.

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

1 Comment

Do not overlook the subtle (though mentioned by Chris) fact that this will return "undefined" when the checkbox isn't checked.
3

This is a bit simpler:

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

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

Comments

1

Just another way:

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

Comments

1

try this,

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

Comments

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

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.