How to add an option to a select with jquery in the first position

0

I have a select which I fill in by clicking on a button, with Jquery $('#lider_id').append("<option value='1' >Josh_reder</option>") But the problem is that .append always puts them at the end of the other option, ie the new one that is entered remains in the last position of the options, what I need is that when adding a new option I put it in the first position, of the options, not in the last one

    
asked by R3d3r 82 09.11.2018 в 23:29
source

2 answers

0

According to the official documentation , you can use .prepend() :

$('#lider_id').prepend("<option value='1' >Josh_reder</option>");

Also, I would recommend you use the following syntax:

let $option = $('<option />', {
    text: 'Josh_reder',
    value: 1,
});
$('#lider_id').prepend($option);

Demonstration code:

$('#prepend').on('click', function () {
  let $lider_list = $('#lider_id option');

  $('#lider_id').prepend($('<option />', {
    text: 'I: Líder ' + ($lider_list.length + 1),
    value: $lider_list.length + 1,
  }));
});

$('#append').on('click', function () {
  let $lider_list = $('#lider_id option');

  $('#lider_id').append($('<option />', {
    text: 'F: Líder ' + ($lider_list.length + 1),
    value: $lider_list.length + 1,
  }));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="lider_id">
  <option value="1">Líder 1</option>
</select>

<button id="prepend">Añadir al inicio</button>
<button id="append">Añadir al final</button>
    
answered by 09.11.2018 / 23:34
source
0

Use the function .prepend instead of .append :

$("#theSelectId").prepend("<option value='Auto 0' selected='selected'>Auto 0</option>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="theSelectId">
  <option value="Auto 1">Auto 1</option>
  <option value="Auto 2">Auto 2</option>
  <option value="Auto 3">Auto 3</option>
  <option value="Auto 4">Auto 4</option>
</select>

The .prepend () method inserts the content specified by the parameter, at the beginning of each element in the set of matching elements (in this case your select ).

You can review the documentation in the following route: link

I hope it helps you. Greetings.

    
answered by 09.11.2018 в 23:34