开发者

a better way to check if a checkbox is defined?

开发者 https://www.devze.com 2023-01-07 05:07 出处:网络
currently i am using var email, fax, sms = false; if($(\'#uemail:checked\').val() != undefined) email = true;

currently i am using

var email, fax, sms = false;  
    if($('#uemail:checked').val() != undefined)  
        email = true;  
    if($('#ufax:checked').val() != undefined)  
        fax = true;  
    if($('#usms:checked').val() != undefined)  
        sms = true;  

but its such a long way to write it.

is ther开发者_StackOverflow中文版e a better way to write this?


Try this:

if($('#uemail').is(':checked'))
    email = true;

Or even shorter:

email = $('#uemail').is(':checked');

You're passing the :checked selector into jQuery's .is() method which returns a boolean value;

  • http://api.jquery.com/is/


You can use .length, like this:

var email = $('#uemail:checked').length,
      fax = $('#ufax:checked').length,
      sms = $('#usms:checked').length;

.length is the length of the array of matched elements...if it's not checked, it's 0. And since .length == 0 serves for .length == false in JavaScript you can do the short version above. If you need a true/false, then just do .length != 0 instead :)

Or, another alternative that produces booleans, just use the DOM .checked property:

var email = $('#uemail')[0].checked,
      fax = $('#ufax')[0].checked,
      sms = $('#usms')[0].checked;

Or, no jQuery at all just use getElementById():

var email = document.getElementById('uemail').checked,
      fax = document.getElementById('ufax').checked,
      sms = document.getElementById('usms').checked;


An alternative may be to use an associative array and then loop through the keys. It would certainly be more DRY.

// Initialise all the checkbox values as unknown
var items = {
  "email" : none,
  "fax"   : none,
  "sms"   : none
};

// Loop through each checkbox index
for (var index in items) {

   // Get the id of the checkbox
   var id = '#u' + index;

   // Find out if the checkbox is checked
   items[index] = $(id).is(':checked');
}
0

精彩评论

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