tags:

views:

37

answers:

1

How can I return null instead of a 'undefined' from a select element.

Basically I have 4 selects at the moment, but only the first one is populated with data at this point, but I want to grab the value from all of them when working with them.

<select class="changeValue" id="drpOne"></select>
<option id=1>1</option>
<option id=2>2</option>
<option id=3>3</option>

<select class="changeValue" id="drpTwo"></select>

JQuery:

$('.changeValue').change(function() {
    var data = {};
    data["Id1"] = $('#drpOne:selected').attr("id");
    data["Id2"] = $('#drpTwo:selected').attr("id");

In this case, drpTwo will return 'undefined'. Is there anyway to get a null instead?

+6  A: 

Use the or operator ||:

data["Id2"] = $('#drpTwo:selected').attr("id") || null;
nickf
Just curious, won't this assign the truth value instead? Thanks
Mahesh Velaga
Nope, Javascript is strange but cool in this way. `x = null || 3; x == 3`, `x = 2 || 3; x == 2`
nickf
No, in JS it'll return the result of first statement if it's not null/undefined (I don't remember exactly right now) or the value of the second one.
Crozin
it returns the first truthy component, or the last one if none are truthy.
nickf
+1 Awesome! Thanks for the clarification :)
Mahesh Velaga