3

I am trying to get values of specific option tags using jQuery.

This is my HTML:

<select name="modele" class="wyszselect" onchange="przenies(this[this.selectedIndex].value);"> <option value="0">Choose model</option> <option value="242">242</option> <option value="243">243</option> <option value="244">244</option> <option value="246">246</option> <option value="320">320</option> <option value="324">324</option> <option value="328">328</option> <option value="33">33</option> </select> 

This is my jQuery code:

$(document).ready(function () { var options = []; $("option").each(function (index, oneOption) { options.push(oneOption.attr("value")) }); console.log(options); }); 

I got this error:

Uncaught TypeError: oneOption.attr is not a function

1
  • oneOption is a dom object, .attr() is a jquery function. You could use oneOption.value Commented Jun 18, 2015 at 10:55

4 Answers 4

4

Conver oneOption to jQuery Object, like so

 $("option").each(function (index, oneOption) { options.push($(oneOption).attr("value")) }); 

Example

Sign up to request clarification or add additional context in comments.

Comments

3

The each function will pass the DOM object instead of jQuery object. Either convert to jQuery object or use the DOM object, like options.push(oneOption.value), this will be faster then converting the DOM object to jQuery object and then calling attr to get the value. You can also use this.value

$("option").each(function (index, oneOption) { //options.push($(oneOption).attr("value")); options.push(oneOption.value); //options.push(this.value); }); 

For getting comma separated value

$("option").map(function(){ return this.value; }).get().join(','); 

2 Comments

@RazvanDumitru do you mean to do console.log(map(options)) ?
@Adil no i mean that the console should print something like this: optinos = ["value1", "value2", "value3", "value4", ....]
1

use map()in jquery() ,and get the option value using this object

options = $("option").map(function (index, oneOption) { return this.value; }).get().join(','); 

DEMO

or in each()

options =[]; $("option").each(function (index, oneOption) { options.push(this.value); }) 

3 Comments

how can I get the result in a form separated in comma ?
your update gives me this result 0,242,243,244,246,320,324,328,33, while i would like this result: ["value", "value", "value" ......]
1

Maybe you need to convert it to a jQuery Element:

$("option").each(function (index, oneOption) { options.push($(oneOption).attr("value")) }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.