简体   繁体   中英

Create select field dynamically - >selected< option doesn't show up

I'm writing a function for dynamic creation of forms with jQuery. Now I stuck at due the selected parameter won't show up by any reason. Here's a Fiddle .

I don't assume this to be a big deal, however I got stuck.

// Creates select element with N options.
// options is an array with options
// name is the elements ID as a string
// selected, optionally, is the selected option. must be the same type as in options

function make_dynamic_select( options, name, selected ){
    select = "<select id='' type='' size ='1', name='" + name + "'>"    
    options.forEach(function(option){
        // a little debug
        console.log(typeof option,option," === ",typeof selected,selected,(option === selected))
        // append the option            
        select += (option === selected)? "<option selected>":"<option>" + option + "</option>"
    });
    return select += "</select>"
};

You are not generating string correctly.

Use

select += (option === selected ? "<option selected>":"<option>" ) + option + "</option>";

DEMO

Here is a DEMO .

function make_dynamic_select( options, name, selected ){

    select = "<select id='' type='' size ='1', name='" + name + "'>"    
    options.forEach(function(option){
        console.log(typeof option,option," === ",typeof selected,selected,(option === selected))

        console.log(option === selected)

                select += (option === selected)? "<option selected>"+option+"</option>":"<option>" + option + "</option>"


    })
    select += "</select>"
    return select
};

$("#foo").append(make_dynamic_select([1,2,3],"bar",2));

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