Insert an option in select in a particular Window

Asked

Viewed 115 times

-1

I have the following select:

<select id="selectChannelCam" class="custom-select">
    <option value="" disabled selected>Selecione</option>
</select>

As you can see, it has only one option that is neither selectable nor selectable. I would like to add new options, but in an orderly way. Sorting is easy, but I need to insert in a specific index, because it is possible that it is necessary to insert for example channel 2 before 1.


I’ve tried to:

$('#selectChannelCam :nth-child(' + index + '))').after("<option value='" + keys[0] +"'>" + keys[0] + "</option>");

and

$("#selectChannelCam :nth-child(" + index + ")").append(new Option(keys[0], keys[0]));
  • The options come from where? ?

  • They depend on another register. When the user registers a channel, this channel should be added to this select. I take everything from a file

  • Then it aims to add options dynamically using a file for guards the options registered by the user, correct?

  • Exactly. I have already been able to put these options in an array, but to add to select (because in the file there is other information too, so I thought I’d put it in the vector)

  • 1

    You can sort this array before and when it is popular select will be just insert.

2 answers

1


You can use the eq(n) to select the index number, and then before() or after() to insert the new element before or after respectively.

Take this example:

$("#btn").click(function() {
    $("#selectChannelCam option").eq(2).before($("<option>Uma nova opção</option>").text("Nova Opção"));   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectChannelCam" class="custom-select">
    <option value="" disabled selected>Selecione</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>
<p>
   <button id="btn">Inserir valor</button>
</p>

The eq(2) selects the element with index 2, and inserts a new option before (before).

  • how do I make the options variable instead of a failed text?

  • just do as in your example that has + index + for example

-1

How to insert an option into a Select widget:

// referência para elemento select
var sel = document.getElementById('selectChannelCam');

// criar um elemento opção
var opt = document.createElement('option');

// Aqui atribui o valor de texto que tem guardado no seu vetor
opt.appendChild( document.createTextNode('Texto que aparece na sua Opção') );

// Aqui atribui o valor da opção que tem guardado no seu vetor
opt.value = 'option value'; 

// Adicionar a opção ao final do elemento select
sel.appendChild(opt); 

Browser other questions tagged

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