views:

62

answers:

3

hi there, 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 there a better way to write this?

+10  A: 

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;

patrick dw
brilliant :) works perfect, and single line
Hailwood
+5  A: 

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;
Nick Craver
Was about to respond to your original comment. :o) Agreed with `[0].checked`, and was about to say that if you're going to shed jQuery, might as well go all the way. Good to see you included it in your answer. :o)
patrick dw
@patrick - Sorry about that, converted it here...comments don't offer enough formatting sometimes, if only we were allowed new-lines...though I do see how that would get abused quickly.
Nick Craver
Nick - Not a problem. It was a good idea that belongs here. :o)
patrick dw
Either of the last two methods is the way to go in my book.
Tim Down
+2  A: 

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');
}
Metalshark