Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there?

Marvellous,

like image 745
RIK Avatar asked Mar 11 '11 10:03

RIK


People also ask

How check if checkbox is checked jQuery?

We can check the status of a checkbox by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') .

How check if checkbox is checked?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.


2 Answers

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.

like image 81
Chris Diver Avatar answered Sep 26 '22 07:09

Chris Diver


This is a bit simpler:

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

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

like image 34
Richard Dalton Avatar answered Sep 25 '22 07:09

Richard Dalton