How to use Jquery functions in array?

Asked

Viewed 88 times

0

I’m selecting a select and trying through the array to access one of the options to place it with the attribute Selected, but every time I try to use the .att("selected", "selected"); get the bug: 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

2 answers

1


You can use the .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>
<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>

  • What would be the index?

  • It would be the position of the option you would like to select, what you intended with $(size[0][1]).attr('selected', 'selected'); ?

1

The problem is you’re using .attr to change the object attribute not jQuery. 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 the size to a jQuery object and use .attr:

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

Or you can put the [0] direct on variable:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.