JSONBUG123
JSONBUG123

Reputation: 111

Save HTML <select> element into variable without creating an array

So, the javascript kinda looks like this:

var test = $('#selectelement')
console.log(test)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Now, when running this code, test becomes an array containing the respective element. So if I want to call this select element from the array, I'd have to code

test[0]

Now, this is not much of an issue of course, but I'd like to avoid it since an array is NOT what I need here because only one single element is saved to this variable.

So is there any way to avoid this behavior and instead just have a "normal" variable created (I know JS only knows objects, but at least syntaxwise it should behave like a "normal" variable/primitive value :D)?

Upvotes: 1

Views: 966

Answers (3)

Ahs N
Ahs N

Reputation: 8366

You can always use

var test = ('#selectelement')[0];

or a more JQuery way,

var test = ('#selectelement').get(0);

to get the first element into the variable directly. You can of course also use native functions like this:

var test = document.querySelector("#selectelement");

which will still give you the only element.

Upvotes: 0

gavgrif
gavgrif

Reputation: 15489

Using the code you had returns the jquery object - what you could do is to get the value of the selected element and use that for the variable. The following code simply updates a variable and consoles it when you change the selected option of the select list.

$('#selectelement').on('change',function(){
  var test = $(this).val();
  console.log(test)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="selectelement">Change me </label>
<select id="selectelement">
  <option selected disabled></option>
  <option>option 1</option>
  <option>option 2</option>
  <option>option 3</option>
  <option>option 4</option>
 </select>

Upvotes: 0

Sari Masri
Sari Masri

Reputation: 226

it's an array because you return a jquery object :

 document.getElementById('contents'); //returns a HTML DOM Object
 var contents = $('#contents')//array

you can store it in one line

 var contents = $('#contents')[0];  //returns a jQuery Object

JavaScript objects act similar to associative arrays

Upvotes: 2

Related Questions