JQuery `.attr ()` is not a function

I am trying to get the values ​​of certain parameter 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

+3


source to share


4 answers


Convert oneOption

to jQuery

Object, for example

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

      



Example

+3


source


Each function passes an object DOM

instead of an object jQuery

. Either convert to jQuery object or use DOM object, for example options.push(oneOption.value)

, it will be faster than converting DOM object to jQuery object and then calling attr

to get value. You can also usethis.value

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

      



To get a comma separated value

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

      

+3


source


use map()

in jquery () and get parameter 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);
})

      

+1


source


You need to transform the jQuery element.

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

      

0


source







All Articles