Array javascript select option selected

Содержание
  1. set option «selected» attribute from dynamic created option
  2. 19 Answers 19
  3. Make option defaultSelected
  4. Make option defaultSelected while dynamically creating options
  5. SELECT.value vs. OPTION.setAttribute vs. OPTION.selected vs. OPTION.defaultSelected
  6. Comparison test of the different methods
  7. Работа с select с помощью JQuery
  8. Получить значение выбранного элемента
  9. Получить текст выбранного элемента
  10. Узнать сколько элементов option в списке select
  11. Узнать количество выбранных элементов
  12. Выбор элементов
  13. Выбрать первый элемент:
  14. Выбрать последний элемент:
  15. Выбрать элемент c value = 2:
  16. Выбрать элемент содержащий текст «виноград»:
  17. Выбрать все элементы:
  18. Снять выделение:
  19. Заблокировать и разблокировать select
  20. Добавление option в select
  21. Добавить элемент в начало select:
  22. Добавить элемент в конец select:
  23. Добавить элемент до и после option c value = 2:
  24. Добавить элемент до и после option c текстом «апельсин»:
  25. Добавление элементов в optgroup
  26. Добавить элементы option в select из массива
  27. Удаление option из select
  28. Удалить выбранный элемент:
  29. Удалить первый элемент:
  30. Удалить элемент c value = 4:
  31. Удалить элемент содержащий текст «виноград»:
  32. Очистить весь select:
  33. Комментарии 5
  34. Другие публикации

set option «selected» attribute from dynamic created option

it fails both in FFX and IE. I need the «Indonesia» option to have selected=»selected» attribute so when I click reset button, it will select «Indonesia» again. changing the js function to dynamically create «country» options is not an option. the solution must work both in FFX and IE. thank you

19 Answers 19

var country = document.getElementById("country"); country.options[country.options.selectedIndex].selected = true; 

Well.. that’s not the response to what was asked, but I like it anyway since I was looking for this kind of approach =)

Apparently from what others have said this doesn’t match the question. However, it was exactly what I needed so thanks!

Читайте также:  Как ловить исключения python

Good question. You will need to modify the HTML itself rather than rely on DOM properties.

var opt = $("option[val=ID]"), html = $("").append(opt.clone()).html(); html = html.replace(/\>/, ' selected="selected">'); opt.replaceWith(html); 

The code grabs the option element for Indonesia, clones it and puts it into a new div (not in the document) to retrieve the full HTML string:.

It then does a string replace to add the attribute selected=»selected» as a string, before replacing the original option with this new one.

I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/

Instead of modifying the HTML itself, you should just set the value you want from the relative option element:

In this case «ID» is the value of the option «Indonesia»

To specify the value that a form field should revert to upon resetting the form, use the following properties:

  • Checkbox or radio button: defaultChecked
  • Any other control: defaultValue
  • Option in a drop down list: defaultSelected

So, to specify the currently selected option as the default:

var country = document.getElementById("country"); country.options[country.selectedIndex].defaultSelected = true; 

It may be a good idea to set the defaultSelected value for every option, in case one had previously been set:

var country = document.getElementById("country"); for (var i = 0; i

Now, when the form is reset, the selected option will be the one you specified.

// get the OPTION we want selected var $option = $('#SelectList').children('option[value="'+ id +'"]'); // and now set the option we want selected $option.attr('selected', true);​​ 

The solution i was looking for! This helps to spot the option with required value! Thank u @corradio!

What you want to do is set the selectedIndex attribute of the select box.

country.options.selectedIndex = index_of_indonesia; 

Changing the ‘selected’ attribute will generally not work in IE. If you really want the behavior you’re describing, I suggest you write a custom javascript reset function to reset all the other values in the form to their default.

var x = document.getElementById("country").children[2]; x.setAttribute("selected", "selected"); 

Make option defaultSelected

HTMLOptionElement.defaultSelected = true; // JS $('selector').prop(); // jQuery 

If the SELECT element is already added to the document (statically or dynamically), to set an option to Attribute- selected and to make it survive a HTMLFormElement.reset() — defaultSelected is used:

const EL_country = document.querySelector('#country'); EL_country.value = 'ID'; // Set SELECT value to 'ID' ("Indonesia") EL_country.options[EL_country.selectedIndex].defaultSelected = true; // Add Attribute selected to Option Element document.forms[0].reset(); // "Indonesia" is still selected
 

The above will also work if you build the options dynamically, and than (only afterwards) you want to set one option to be defaultSelected .

const countries = < AF: 'Afghanistan', AL: 'Albania', HR: 'Croatia', ID: 'Indonesia', ZW: 'Zimbabwe', >; const EL_country = document.querySelector('#country'); // (Bad example. Ideally use .createDocumentFragment() and .appendChild() methods) EL_country.innerHTML = Object.keys(countries).reduce((str, key) => str += `">$ `, ''); EL_country.value = 'ID'; EL_country.options[EL_country.selectedIndex].defaultSelected = true; document.forms[0].reset(); // "Indonesia" is still selected

Option gets Attribute selected by using defaultSelected

Make option defaultSelected while dynamically creating options

To make an option selected while populating the SELECT Element, use the Option() constructor MDN

var optionElementReference = new Option(text, value, defaultSelected, selected);

const countries = < AF: 'Afghanistan', AL: 'Albania', HR: 'Croatia', ID: 'Indonesia', // ; const EL_country = document.querySelector('#country'); const DF_options = document.createDocumentFragment(); Object.keys(countries).forEach(key => < const isIndonesia = key === 'ID'; // Boolean DF_options.appendChild(new Option(countriesArray javascript select option selected, key, isIndonesia, isIndonesia)) >); EL_country.appendChild(DF_options); document.forms[0].reset(); // "Indonesia" is still selected

In the demo above Document.createDocumentFragment is used to prevent rendering elements inside the DOM in a loop. Instead, the fragment (containing all the Options) is appended to the Select only once.

SELECT.value vs. OPTION.setAttribute vs. OPTION.selected vs. OPTION.defaultSelected

Although some (older) browsers interpret the OPTION’s selected attribute as a «string» state, the WHATWG HTML Specifications html.spec.whatwg.org state that it should represent a Boolean selectedness

The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute.
html.spec.whatwg.org — Option selectedness

one can correctly deduce that just the name selected in is enough to set a truthy state.

Comparison test of the different methods

const EL_select = document.querySelector('#country'); const TPL_options = `      `; // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver const mutationCB = (mutationsList, observer) => < mutationsList.forEach(mu => < const EL = mu.target; if (mu.type === 'attributes') < return console.log(`* Attribute $Mutation. $($)`); > >); >; // (PREPARE SOME TEST FUNCTIONS) const testOptionsSelectedByProperty = () => < const test = 'OPTION with Property selected:'; try < const EL = [. EL_select.options].find(opt =>opt.selected); console.log(`$ $($) PropSelectedValue: $`); > catch (e) < console.log(`$NOT FOUND!`); > > const testOptionsSelectedByAttribute = () => < const test = 'OPTION with Attribute selected:' try < const EL = [. EL_select.options].find(opt =>opt.hasAttribute('selected')); console.log(`$ $($) AttrSelectedValue: $`); > catch (e) < console.log(`$NOT FOUND!`); > > const testSelect = () => < console.log(`SELECT value:$selectedIndex:$`); > const formReset = () => < EL_select.value = ''; EL_select.innerHTML = TPL_options; // Attach MutationObserver to every Option to track if Attribute will change [. EL_select.options].forEach(EL_option =>< const observer = new MutationObserver(mutationCB); observer.observe(EL_option, ); >); > // ----------- // LET'S TEST! console.log('\n1. Set SELECT value'); formReset(); EL_select.value = 'AL'; // Constatation: MutationObserver did NOT triggered. testOptionsSelectedByProperty(); testOptionsSelectedByAttribute(); testSelect(); console.log('\n2. Set HTMLElement.setAttribute()'); formReset(); EL_select.options[2].setAttribute('selected', true); // MutationObserver triggers testOptionsSelectedByProperty(); testOptionsSelectedByAttribute(); testSelect(); console.log('\n3. Set HTMLOptionElement.defaultSelected'); formReset(); EL_select.options[3].defaultSelected = true; // MutationObserver triggers testOptionsSelectedByProperty(); testOptionsSelectedByAttribute(); testSelect(); console.log('\n4. Set SELECT value and HTMLOptionElement.defaultSelected'); formReset(); EL_select.value = 'ZW' EL_select.options[EL_select.selectedIndex].defaultSelected = true; // MutationObserver triggers testOptionsSelectedByProperty(); testOptionsSelectedByAttribute(); testSelect(); /* END */ console.log('\n*. Getting MutationObservers out from call-stack. ');

Although the test 2. using .setAttribute() seems at first the best solution since both the Element Property and Attribute are unison, it can lead to confusion, specially because .setAttribute expects two parameters:

EL_select.options[1].setAttribute('selected', false); // // But still selected! 

will actually make the option selected

Should one use .removeAttribute() or perhaps .setAttribute(‘selected’, . ) to another value? Or should one read the state by using .getAttribute(‘selected’) or by using .hasAttribute(‘selected’) ?

Instead test 3. (and 4.) using defaultSelected gives the expected results:

  • Attribute selected as a named Selectedness state.
  • Property selected on the Element Object, with a Boolean value.

Источник

Работа с select с помощью JQuery

Сборник методов JQuery для работы с выпадающими списками .

Получить значение выбранного элемента

$('#select').val(); /* или */ $('select[name=fruct]').val();

Для списков с множественном выбором (multiple) метод val() вернет значения в виде массива.

Получить текст выбранного элемента

$('#select option:selected').text(); /* или */ $('#select option:selected').html();

Узнать сколько элементов option в списке select

Узнать количество выбранных элементов

$('#select option:selected').size();

Выбор элементов

Выбрать первый элемент:

$('#select option:first').prop('selected', true);

Выбрать последний элемент:

$('#select option:last').prop('selected', true);

Выбрать элемент c value = 2:

$('#select option[value=2]').prop('selected', true);

Выбрать элемент содержащий текст «виноград»:

$('#select option:contains("виноград")').prop('selected', true);

Выбрать все элементы:

$('#select option').prop('selected', true);

Снять выделение:

$('#select option').prop('selected', false);

Заблокировать и разблокировать select

// Заблокировать $('#select').prop('disabled', true); // Разблокировать $('#select').prop('disabled', false); 

Добавление option в select

Добавить элемент в начало select:

$('#select').prepend('');

Добавить элемент в конец select:

Добавить элемент до и после option c value = 2:

// До $('#select option[value=2]').before(''); // После $('#select option[value=2]').after(''); 

Добавить элемент до и после option c текстом «апельсин»:

// До $('#select option:contains("апельсин")').before(''); // После $('#select option:contains("апельсин")').after('');

Добавление элементов в optgroup

// Добавить элемент в начало группы «Фрукты» $('#select optgroup[label=Фрукты]').prepend(''); // Добавить элемент в конец группы «Фрукты» $('#select optgroup[label=Фрукты]').append('');

Добавить элементы option в select из массива

var array = ; $.each(array, function(key, value) < $('#select').append(''); >);

Удаление option из select

Удалить выбранный элемент:

$('#select option:selected').remove();

Удалить первый элемент:

Удалить элемент c value = 4:

$('#select option[value=4]').remove();

Удалить элемент содержащий текст «виноград»:

$('#select option:contains("виноград")').remove();

Очистить весь select:

$('#select').empty(); /* или */ $('#select option').remove();

Комментарии 5

Здравствуйте! Спасибо за статью, но подскажите как выбрать несколко значений select, если у меня multiple
У вас написано как выбрать с одним значением:

$('#select option[value=2]').prop('selected', true);

А как сделать если нужно выбрать со значением например 2 и 3?
Пробовал так: $(‘#select option[value=2,3]’).prop(‘selected’, true);
Но выдает ошибку.

var array = ; 

$.each(array, function(key, value) $(`#select option[value="$"]`).prop('selected', true);
>);
Выбрать элемент c value = 2:
$('#select option[value=2]').prop('selected', true);
JS
Выбрать элемент содержащий текст «виноград»:
$('#select option:contains("виноград")').prop('selected', true);

Не работают эти конструкции. Выдаются ошибки. Эти примеры по всему интернету, но у меня не получается таким образом выбрать позицию, да и сам phpstorm ругается, что г@&но какое-то ввёл.

кто подскажет куда нужно прописать сумму и количество дней что рассчитать стоимость и срок
/*Калькулятор*/
function calculate() let sum = parseInt($(«#SelectSiteType option:selected»).val()) + parseInt($(«#SelectDesign option:selected»).val()) + parseInt($(«#SelectAdaptability option:selected»).val());
let days = parseInt($(«#SelectSiteType option:selected»).attr(«days»)) + parseInt($(«#SelectDesign option:selected»).attr(«days»)) + parseInt($(«#SelectAdaptability option:selected»).attr(«days»));
$(» .digit»).text(sum);
$(» .digit1″).text(days);
>;
calculate();
$(«select»).on(«change», function() calculate();
>);

Авторизуйтесь, чтобы добавить комментарий.

Другие публикации

Селекторы JQuery

В jQuery, селекторы в основном позаимствованы из CSS 1-3, также добавлены свои, что дало хороший набор инструментов для манипуляций с элементами в документе.

Источник

Оцените статью