jawo
jawo

Reputation: 896

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>"
};

Upvotes: 0

Views: 38

Answers (2)

guvenckardas
guvenckardas

Reputation: 738

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));

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You are not generating string correctly.

Use

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

DEMO

Upvotes: 1

Related Questions