Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return 'null' instead of 'undefined' from select element

Tags:

jquery

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?

like image 284
MrW Avatar asked Jan 23 '23 10:01

MrW


1 Answers

Use the or operator ||:

data["Id2"] = $('#drpTwo:selected').attr("id") || null;
like image 113
nickf Avatar answered Feb 15 '23 09:02

nickf