Nice programing

동적 생성 옵션에서 옵션 "선택"속성 설정

nicepro 2020. 12. 2. 21:57
반응형

동적 생성 옵션에서 옵션 "선택"속성 설정


자바 스크립트 함수를 사용하여 동적으로 생성 된 선택 옵션이 있습니다. 선택 개체는

<select name="country" id="country">
</select>

js 함수가 실행될 때 "country"객체는

<select name="country" id="country">
    <option value="AF">Afghanistan</option>
    <option value="AL">Albania</option>
    ...
    <option value="ID">Indonesia</option>
    ...
    <option value="ZW">Zimbabwe</option>
</select>

기본 선택 옵션으로 "인도네시아"를 표시합니다. 참고 : selected="selected"해당 옵션 에는 속성 이 없습니다 .

그런 다음 selected="selected"속성을 "Indonesia" 로 설정해야 합니다.

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

방화범을 사용하면 "인도네시아"옵션이 다음과 같습니다.

<option value="ID" selected="selected">Indonesia</option>

그러나 IE에서는 실패합니다 (IE 8에서 테스트 됨).

그런 다음 jQuery를 사용해 보았습니다.

$( function() {
    $("#country option:selected").attr("selected", "selected");
});

FFX와 IE 모두에서 실패합니다.

selected="selected"속성 을 가지려면 "인도네시아"옵션이 필요 하므로 재설정 버튼을 클릭하면 "인도네시아"가 다시 선택됩니다.

js 함수를 변경하여 "국가"옵션을 동적으로 만드는 것은 옵션이 아닙니다. 솔루션은 FFX와 IE에서 모두 작동해야합니다.

감사합니다


좋은 질문. DOM 속성에 의존하는 대신 HTML 자체를 수정해야합니다.

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

이 코드는 인도네시아의 옵션 요소를 가져 와서 복제 한 다음 문서가 아닌 새 div에 넣어 전체 HTML 문자열을 검색합니다 <option value="ID">Indonesia</option>.

그런 다음 원래 옵션을이 새 옵션으로 바꾸기 전에 문자열 바꾸기를 수행하여 속성 selected="selected" 을 문자열로 추가합니다 .

IE7에서 테스트했습니다. 여기에서 재설정 버튼이 제대로 작동하는지 확인하십시오 : http://jsfiddle.net/XmW49/


당신은 그것을 지나치게 생각하고 있습니다.

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

HTML 자체를 수정하는 대신 상대 옵션 요소에서 원하는 값을 설정해야합니다.

$(function() {
    $("#country").val("ID");
});

이 경우 "ID"는 "Indonesia"옵션의 값입니다.


너무 많은 오답!

양식을 재설정 할 때 양식 필드를 되돌려 야하는 값을 지정하려면 다음 속성을 사용합니다.

  • 체크 박스 또는 라디오 버튼 : defaultChecked
  • 기타 <input>제어 :defaultValue
  • 드롭 다운 목록의 옵션 : defaultSelected

따라서 현재 선택된 옵션을 기본값으로 지정하려면 :

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

defaultSelected이전에 설정 한 경우 모든 옵션에 대한 을 설정하는 것이 좋습니다 .

var country = document.getElementById("country");
for (var i = 0; i < country.options.length; i++) {
    country.options[i].defaultSelected = i == country.selectedIndex;
}

이제 양식이 재설정되면 선택한 옵션이 지정한 옵션이됩니다.


// 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);​​

원하는 것은 선택 상자의 selectedIndex 속성을 설정하는 것입니다.

country.options.selectedIndex = index_of_indonesia;

'selected'속성을 변경하는 것은 일반적으로 IE에서 작동하지 않습니다. 설명하는 동작 정말로 원한다면 양식의 다른 모든 값을 기본값으로 재설정하는 사용자 지정 자바 스크립트 재설정 함수를 작성하는 것이 좋습니다.


이것은 FF, IE9에서 작동합니다.

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

// Get <select> object
var sel = $('country');

// Loop through and look for value match, then break
for(i=0;i<sel.length;i++) { if(sel.value=="ID") { break; } }

// Select index 
sel.options.selectedIndex = i;

Begitu loh.


올바른 값을 찾을 때까지 모든 옵션 값을 검색 할 수 있습니다.

var defaultVal = "Country";
$("#select").find("option").each(function () {

    if ($(this).val() == defaultVal) {

        $(this).prop("selected", "selected");
    }
});

작동합니다.

$("#country [value='ID']").attr("selected","selected");

요소에 바인딩 된 함수 호출이있는 경우 다음과 같이

$("#country").change();

select = document.getElementById('selectId');
var opt = document.createElement('option');
    opt.value = 'value';
    opt.innerHTML = 'name';
    opt.selected = true;
    select.appendChild(opt);

옵션을 기본값으로 설정

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

HTMLOptionElement MDN

select 요소가 이미 문서 (정적 또는 동적)에 추가되면, Attribute-에 옵션을 설정 selected하고 만드는 그것은 생존HTMLFormElement.reset() - defaultSelected사용된다 :

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
<form>
  <select name="country" id="country">
    <option value="AF">Afghanistan</option>
    <option value="AL">Albania</option>
    <option value="HR">Croatia</option>
    <option value="ID">Indonesia</option>
    <option value="ZW">Zimbabwe</option>
  </select>
</form>

위는 당신이 옵션도 작업을 구축 할 것입니다 경우 동적으로 , 그리고 (보다 만 이후 ) 당신은 할 하나의 옵션을 설정합니다 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 += `<option value="${key}">${countries[key]}</option>`, ''); 

EL_country.value = 'ID';
EL_country.options[EL_country.selectedIndex].defaultSelected = true;

document.forms[0].reset(); // "Indonesia" is still selected
<form>
  <select name="country" id="country"></select>
</form>

옵션은 defaultSelected를 사용하여 선택된 속성을 가져옵니다.

옵션을 동적으로 생성하는 동안 옵션을 defaultSelected로 설정

selected SELECT 요소를 채우는 동안 옵션을 만들려면 생성자 MDN을 사용하십시오.Option()

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

const countries = {
  AF: 'Afghanistan',
  AL: 'Albania',
  HR: 'Croatia',
  ID: 'Indonesia',     // <<< make this one defaultSelected
  ZW: 'Zimbabwe',
};

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(countries[key], key, isIndonesia, isIndonesia))
});

EL_country.appendChild(DF_options);

document.forms[0].reset(); // "Indonesia" is still selected
<form>
  <select name="country" id="country"></select>
</form>

위의 데모에서 Document.createDocumentFragment 는 루프에서 DOM 내부의 요소를 렌더링하는 것을 방지하는 데 사용됩니다. 대신 모든 옵션이 포함 된 조각이 선택 항목에 한 번만 추가됩니다.


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

일부 (이상) 브라우저 옵션의 해석하지만 selectedA와 속성을 "문자열" 상태는 WHATWG HTML 사양 html.spec.whatwg.org 는 부울 표현해야한다고 상태 selectedness을

옵션 요소의 선택성부울 상태 이며 처음에는 false입니다. 별도로 지정된 경우를 제외하고 요소가 생성 될 때 요소에 선택된 속성이있는 경우 해당 선택성은 true로 설정되어야합니다.
html.spec.whatwg.org-옵션 선택성

하나는 수 정확하게 그 이름 만 추론 selected<option value="foo" selected>truthy 상태를 설정하기에 충분하다.


다른 방법의 비교 테스트

const EL_select = document.querySelector('#country');
const TPL_options = `
  <option value="AF">Afghanistan</option>
  <option value="AL">Albania</option>
  <option value="HR">Croatia</option>
  <option value="ID">Indonesia</option>
  <option value="ZW">Zimbabwe</option>
`;

// 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 ${mu.attributeName} Mutation. ${EL.value}(${EL.text})`);
    }
  });
};

// (PREPARE SOME TEST FUNCTIONS)

const testOptionsSelectedByProperty = () => {
  const test = 'OPTION with Property selected:';
  try {
    const EL = [...EL_select.options].find(opt => opt.selected);
    console.log(`${test} ${EL.value}(${EL.text}) PropSelectedValue: ${EL.selected}`);
  } catch (e) {
    console.log(`${test} NOT FOUND!`);
  }
} 

const testOptionsSelectedByAttribute = () => {
  const test = 'OPTION with Attribute selected:'
  try {
    const EL = [...EL_select.options].find(opt => opt.hasAttribute('selected'));
    console.log(`${test} ${EL.value}(${EL.text}) AttrSelectedValue: ${EL.getAttribute('selected')}`);
  } catch (e) {
    console.log(`${test} NOT FOUND!`);
  }
} 

const testSelect = () => {
  console.log(`SELECT value:${EL_select.value} selectedIndex:${EL_select.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, {attributes: true});
  });
}

// -----------
// 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...');
<form>
  <select name="country" id="country"></select>
</form>

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);
// <option value="AL" 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.

To set the input option at run time try setting the 'checked' value. (even if it isn't a checkbox)

elem.checked=true;

Where elem is a reference to the option to be selected.

So for the above issue:

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

This works for me, even when the options are not wrapped in a .

If all of the tags share the same name, they should uncheck when the new one is checked.


Realize this is an old question, but with the newer version of JQuery you can now do the following:

$("option[val=ID]").prop("selected",true);

This accomplishes the same thing as Box9's selected answer in one line.


The ideas on this page were helpful, yet as ever my scenario was different. So, in modal bootstrap / express node js / aws beanstalk, this worked for me:

var modal = $(this);
modal.find(".modal-body select#cJourney").val(vcJourney).attr("selected","selected");

Where my select ID = "cJourney" and the drop down value was stored in variable: vcJourney


$(...).val()기능을 사용하여 이와 같은 것을 시도 했지만 기능이 존재하지 않았습니다. 다음과 같은 방법으로 값을 수동으로 설정할 수 있습니다 <input>.

// Set value to Indonesia ("ID"):
$('#country').value = 'ID'

... 선택에서 자동으로 업데이트됩니다. 적어도 Firefox에서 작동합니다. 다른 곳에서도 시도해 볼 수 있습니다.

참고 URL : https://stackoverflow.com/questions/4590311/set-option-selected-attribute-from-dynamic-created-option

반응형