Javascript select add option selected

Как сделать option в select :selected с помощью js?

var x = «Терпила»;
Как сделать option :selected в зависимости от переменной x?

KorniloFF

   

leni_m

leni_m

leni_m, ну серьёзно, ты хочешь выставить _значение_ инпута не используя его аттрибут value? Оксюморон.

leni_m

Илья Агафонов, он есть, но он отличается от того, что внутри тега и не хочется 200+ опций переписывать вручную. А получаю я в переменную x именно не value, а то, что внутри.

$("#select option").filter(function() < return $(this).text() === text; >).first().attr("value")

leni_m

Илья Агафонов, да у меня раньше input обычный был, теперь селект понадобилось сделать, в обработчике ковыряться не хочу, поэтому просто из селекта передаю в инпут type=»hidden», а чтобы при неправильно заполненной форме, сохранялся селект, беру значение из инпута, и оно как раз такое, какое внутри тегов)

KorniloFF

   

value для каждого из option . Иначе, какое значение вы будете передавать при submit формы? Сделать это проще простого:

const select = document.querySelector('#select').getElementsByTagName('option'); for (let i = 0; i

Если, всё-таки, каким-то неведомым образом нужно обойтись без значения value в option , то условие в цикле нужно переписать на вот это:

for (let i = 0; i < select.length; i++) < if (select[i].textContent === 'Терпила') select[i].selected = true; // Или вот на это, если там присутствует html, например: // if (select[i].innerHTML === '

Терпила

') select[i].selected = true; >

leni_m

да у меня значение селекта идет в инпут type=»hidden»
просто понадобилось сделать селект, а обработчик уже готов, и не хочется там тоже ковыряться, раньше инпут был обычным а теперь селект сделать пришлось, а в нем названия стран, где есть value, но он например у России «RU», и не хочется для всех стран вручную переписывать. Нельзя ли вот что написано в option, то и передать?

Источник

Manipulation of HTML Select Element with Javascript

Manipulation of the element with Javascript is quite commonly required in web applications. This tutorial explains how you can perform common operations on select element with vanilla Javascript — adding/deleting options or getting/setting the selected options.

Important Properties and Methods of Select Element

  • value : It gives the value of the first selected option (a multi-valued select may have multiple selected options)
  • options : It gives the list of all option elements in the select
  • selectedOptions : It gives the list of option elements that are currently selected
  • selectedIndex : It is an integer that gives the index of first selected option. In case no option is selected, it gives -1
  • add() : This method adds a new option to the list of options
  • remove() : This method removes an option from the select element

Important Properties of Option Element

  • value : It gives the value of the option
  • text : It gives the text inside the option
  • selected : It tells whether the option is selected or not

Setting Value of Select Element

For a single valued select, setting its value can be done with the value or the selectedIndex property.

// Set option with value 'Orange' as selected document.querySelector('#choose-fruit').value = 'Orange'; // Set the option with index 2 as selected => Sets the 'Banana' option as selected document.querySelector('#choose-fruit').selectedIndex = 2; 

For a multiple valued select, setting multiple selected options can be done by setting the selected attribute of the required option.

  
// choose the first option document.querySelector('#choose-fruit-multiple').options[0].selected = true; // also choose the third option document.querySelector('#choose-fruit-multiple').options[2].selected = true; 

This will obviously work for single valued select also, but using the value property is much direct for them.

Getting the Value and Text/Label of the Selected Options

The selectedOptions property of the select element gives the list of options that are currently selected. Each element in this list is a DOM element — so you can use the value and text property to get the value and inside text of the option.

// For a normal select (and not multi-select) the list would contain only a single element var text = document.querySelector('#choose-fruit').selectedOptions[0].text; var value = document.querySelector('#choose-fruit').selectedOptions[0].value; 

For a multiple select element, you can loop over the list to get all selected options.

  
var selected_options = document.querySelector('#choose-fruit-multiple').selectedOptions; for(var i=0; i // output Orange 2 Grapes 5 

Adding an Option

The add method can be used to add a new option in the select. You can also specify the exact positon where the option needs to be inserted.

var option = document.createElement('option'); option.text = 'BMW'; // append option at the end // new options will be Volvo, Audi, Mercedes & BMW document.querySelector('#choose-car').add(option, null); 
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 0 // new options will be BMW, Volvo, Audi & Mercedes document.querySelector('#choose-car').add(option, 0); 
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 2 // new options will be Volvo, Audi, BMW & Mercedes document.querySelector('#choose-car').add(option, 2); 

Deleting an Option

The remove method can be used to delete an option at a specified index.

// remove the option at index 1 // new options will be Volvo & Mercedes document.querySelector('#choose-car').remove(1); 

Источник

Читайте также:  Python виртуальное окружение pip
Оцените статью