Adding options to select with javascript

后端 未结 9 983
执念已碎
执念已碎 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/

    0 讨论(0)
  • 2020-11-22 16:05

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

    $('#mySelect')
          .append($('<option>', { value : key })
          .text(value)); 
    
    0 讨论(0)
  • 2020-11-22 16:07

    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;
    
    0 讨论(0)
提交回复
热议问题