简体   繁体   中英

loop for select box value

I want to create loop in select box. But I want one code for different select. I am able create for one select but I want for multiple .

for single: with id

I want to change this code according class or for multiple select. My code for this:

<select class="foo"></select><select class="foo"></select>

and:

$(document).ready(function() {
    var elm = document.getElementByClass('foo'),
    df = document.createDocumentFragment();
    for (var i = 0; i <= 60; i++) {
        var option = document.createElement('option');
        option.value = i;
        option.appendChild(document.createTextNode(" " + i));
        df.appendChild(option);
    }
    elm.appendChild(df);
});

I think what you want is

document.getElementsByClassName('foo');

http://jsfiddle.net/5J29g/48/

You can use class selector along with .append() and .clone()

$(document).ready(function () {
    var df = document.createDocumentFragment();
    for (var i = 0; i <= 60; i++) {
        var option = document.createElement('option');
        option.value = i;
        option.appendChild(document.createTextNode(" " + i));
        df.appendChild(option);
    }
    $('.foo').append(function () {
        return $(df).clone()
    })
});

Demo: Fiddle

Since you are using jQuery, so you could do like:

The demo.

$('.foo').each(function() {
    for (var i = 0; i <= 60; i++) {
        $('<option />').val(i).html('#option ' + i).appendTo($(this));
    }
});

I just updated your jsfiddle adding this:

(function() {
var foos=document.querySelectorAll(".foo");
for(var j=0;j<foos.length;j++){
    var elm = foos[j],
        df = document.createDocumentFragment();
        for (var i = 1; i <= 42; i++) {
            var option = document.createElement('option');
            option.value = i;
            option.appendChild(document.createTextNode("option #" + i));
            df.appendChild(option);
        }
        elm.appendChild(df);
    }  
}());

sample check that out, DEMO

Try this:

$('.foo').each(function(){
   // call your code create option element here with $(this).append()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM