How to use Jquery functions in array?

0

I'm selecting a select and trying to access one of the options to place it with the selected attribute, but whenever I try to use .att("selected", "selected"); I get the error: TypeError: size[0][1].attr is not a function

Select:

<select id="size" name="size" class="selectpicker" data-title="Tamanho" data-style="btn-default btn-block" data-menu-style="dropdown-blue">
      <option value="PP" >PP</option>
      <option value="P">P</option>
      <option value="M">M</option>
      <option value="G">G</option>
      <option value="GG">GG</option>
      <option value="XGG">XGG</option>
      <option value="XXXG">XXXGG</option>
</select>

Jquery:

var size = $("#size");
size[0][1].attr('selected', 'selected');

Error:

TypeError: size[0][1].attr is not a function
    
asked by anonymous 08.01.2018 / 21:12

2 answers

1

You can use .get()

$(document).ready(function(){
  var size = $("#size");
  var index = 1  //seu 1;
  $(size.find('option').get(index)).attr('selected', 'selected');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="size" name="size" class="selectpicker" data-title="Tamanho" data-style="btn-default btn-block" data-menu-style="dropdown-blue">
      <option value="PP" >PP</option>
      <option value="P">P</option>
      <option value="M">M</option>
      <option value="G">G</option>
      <option value="GG">GG</option>
      <option value="XGG">XGG</option>
      <option value="XXXG">XXXGG</option>
</select>
    
08.01.2018 / 21:25
1

The problem is that you are using .attr to change the attribute of the non-jQuery object. The jQuery objects must be inside $() .

If you want to use pure JavaScript, you would have to use .setAttribute :

var size = $("#size");
size[0][1].setAttribute('selected', 'selected');

Or convert size to a jQuery object and use .attr :

var size = $("#size");
$(size[0][1]).attr('selected', 'selected');

Or you can put [0] direct in variable:

size = $("#size")[0];
size[1].setAttribute('selected', 'selected');
    
08.01.2018 / 22:57