Adding options to select with javascript

后端 未结 9 1108
执念已碎
执念已碎 2020-11-22 15:40

I want this javascript to create options from 12 to 100 in a select with id=\"mainSelect\", because I do not want to create all of the option tags manually. Can you give me

9条回答
  •  渐次进展
    2020-11-22 16:02

    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/

提交回复
热议问题