Programing

자바 스크립트로 선택할 옵션 추가

lottogame 2020. 6. 17. 20:27
반응형

자바 스크립트로 선택할 옵션 추가


모든 옵션 태그를 수동으로 생성하고 싶지 않기 때문에이 자바 스크립트가 id = "mainSelect"를 사용하여 선택에서 12에서 100 사이의 옵션을 생성하려고합니다. 당신은 몇 가지 포인터를 줄 수 있습니까? 감사

function selectOptionCreate() {

  var age = 88;
  line = "";
  for (var i = 0; i < 90; i++) {
    line += "<option>";
    line += age + i;
    line += "</option>";
  }

  return line;
}

간단한 for루프로 이것을 달성 할 수 있습니다 :

var min = 12,
    max = 100,
    select = document.getElementById('selectElementId');

for (var i = min; i<=max; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = i;
    select.appendChild(opt);
}

JS 피들 데모 .

내 것과 Sime Vidas의 대답에 대한 JS Perf 비교는 그의 것보다 내 생각이 좀 더 이해 가능하고 직관적이라고 생각하고 그것이 어떻게 구현으로 변환되는지 궁금해했기 때문에 실행됩니다. Chromium 14 / Ubuntu 11.04에 따르면 광산이 다소 빠르지 만 다른 브라우저 / 플랫폼은 결과가 다를 수 있습니다.


OP의 의견에 따라 편집 :

[어떻게] [I] 둘 이상의 요소에 적용합니까?

function populateSelect(target, min, max){
    if (!target){
        return false;
    }
    else {
        var min = min || 0,
            max = max || min + 100;

        select = document.getElementById(target);

        for (var i = min; i<=max; i++){
            var opt = document.createElement('option');
            opt.value = i;
            opt.innerHTML = i;
            select.appendChild(opt);
        }
    }
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);

// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');

// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);

JS 피들 데모 .

And, finally (after quite a delay...), an approach extending the prototype of the HTMLSelectElement in order to chain the populate() function, as a method, to the DOM node:

HTMLSelectElement.prototype.populate = function (opts) {
    var settings = {};

    settings.min = 0;
    settings.max = settings.min + 100;

    for (var userOpt in opts) {
        if (opts.hasOwnProperty(userOpt)) {
            settings[userOpt] = opts[userOpt];
        }
    }

    for (var i = settings.min; i <= settings.max; i++) {
        this.appendChild(new Option(i, i));
    }
};

document.getElementById('selectElementId').populate({
    'min': 12,
    'max': 40
});

JS Fiddle demo.

References:


Here you go:

for ( i = 12; i <= 100; i += 1 ) {
    option = document.createElement( 'option' );
    option.value = option.text = i;
    select.add( option );
}

Live demo: http://jsfiddle.net/mwPb5/


Update: Since you want to reuse this code, here's the function for it:

function initDropdownList( id, min, max ) {
    var select, i, option;

    select = document.getElementById( id );
    for ( i = min; i <= max; i += 1 ) {
        option = document.createElement( 'option' );
        option.value = option.text = i;
        select.add( option );
    }
}

Usage:

initDropdownList( 'mainSelect', 12, 100 );

Live demo: http://jsfiddle.net/mwPb5/1/


I don't recommend doing DOM manipulations inside a loop -- that can get expensive in large datasets. Instead, I would do something like this:

var elMainSelect = document.getElementById('mainSelect');

function selectOptionsCreate() {
  var frag = document.createDocumentFragment(),
    elOption;
  for (var i=12; i<101; ++i) {
    elOption = frag.appendChild(document.createElement('option'));
    elOption.text = i;
  }
  elMainSelect.appendChild(frag);
}

You can read more about DocumentFragment on MDN, but here's the gist of it:

It is used as a light-weight version of Document to store a segment of a document structure comprised of nodes just like a standard document. The key difference is that because the document fragment isn't part of the actual DOM's structure, changes made to the fragment don't affect the document, cause reflow, or incur any performance impact that can occur when changes are made.


The one thing I'd avoid is doing DOM operations in a loop to avoid repeated re-renderings of the page.

var firstSelect = document.getElementById('first select elements id'),
    secondSelect = document.getElementById('second select elements id'),
    optionsHTML = [],
    i = 12;

for (; i < 100; i += 1) {
  optionsHTML.push("<option value=\"Age" + i + "\">Age" + i + "</option>";
}

firstSelect.innerHTML = optionsHTML.join('\n');
secondSelect.innerHTML = optionsHTML.join('\n');

Edit: removed the function to show how you can just assign the html you've built up to another select element - thus avoiding the unnecessary looping by repeating the function call.


See: What is the best way to add options to a select from an array with jQuery?

$('#mySelect')
      .append($('<option>', { value : key })
      .text(value)); 

When you create a new Option object, there are two parameters to pass: The first is the text you want to appear in the list, and the second the value to be assigned to the option.

var myNewOption = new Option("TheText", "TheValue");

You then simply assign this Option object to an empty array element, for example:

document.theForm.theSelectObject.options[0] = myNewOption;

The most concise and intuitive way would be:

var selectElement = document.getElementById('ageselect');

for (var age = 12; age <= 100; age++) {
  selectElement.add(new Option(age));
}
Your age: <select id="ageselect"><option value="">Please select</option></select>

You can also differentiate the name and the value or add items at the start of the list with additional parameters to the used functions:
HTMLSelect​Element​.add(item[, before]);
new Option(text, value, defaultSelected, selected);


None of the above solutions worked for me. Append method didn't give error when i tried but it didn't solve my problem. In the end i solved my problem with data property of select2. I used json and got the array and then give it in select2 element initialize. For more detail you can see my answer at below post.

https://stackoverflow.com/a/41297283/4928277


Often you have an array of related records, I find it easy and fairly declarative to fill select this way:

selectEl.innerHTML = array.map(c => '<option value="'+c.id+'">'+c.name+'</option>').join('');

This will replace existing options.
You can use selectEl.insertAdjacentHTML('afterbegin', str); to add them to the top instead.
And selectEl.insertAdjacentHTML('beforeend', str); to add them to the bottom of the list.

IE11 compatible syntax:

array.map(function (c) { return '<option value="'+c.id+'">'+c.name+'</option>'; }).join('');

참고URL : https://stackoverflow.com/questions/8674618/adding-options-to-select-with-javascript

반응형