August 11, 2012

how can make the slect element and append options?

Question by 3gwebtrain

I am simply trying to make a selector component with some of the options, i am not get any result it this. really some thing wrong the way what i do.

any one can help me in this?

var object = {
               "id":"countries",
               "label":"Country",
               "name":"countries",
               "type":"select",
               "options":[
                  {
                     "value":"",
                     "text":"Select Country"
                  },
                  {
                     "value":"in",
                     "text":"India",
                      "selected":"true"
                  },
                  {
                     "value":"us",
                     "text":"United Stated"

                  },
                  {
                     "value":"uk",
                     "text":"United Kingdom"
                  },
                  {
                     "value":"cn",
                     "text":"Canada"
                  }
               ]
};
var select = "";

var mapInfo = function (element,info) {
    $.map(info, function(val,num){
console.log(val);        
    })
}

var generateSelector = function (info){

    select +='<select'+info.id+'></select>'
    select +=mapInfo(select,info.options)

   $('body').append(select);

}(object);

jsfiddle here

Answer by undefined

Try this:

var $select = $("<select id='"+obj.id+"' name='"+obj.name+"'/>");
var selected = '';
var generateSelector = function (info){
    $.each(obj.options, function(i, ob){
        if (ob.hasOwnProperty('selected')) {
             selected = ob.value;
        }
        $select.append('<option value='+ob.value+'>'+ ob.text+'</option>')
    })

   $('body').append($select);
   $('select').val(selected)
}

Demo

Answer by Starx

Here is my version of the generator. 🙂

$(object).each(function(i,v) {
    var label = $("<label />", { html: v.label, 'for': v.name });
    var element;
    switch(v.type) {
        case "select":
            element = $("<select />", { id: v.id, name: v.name  });
            $(v.options).each(function(x,y) {
                var option = $("<option />", { value : y.value, html : y.text });
                element.append(option)
            });
        break;
    }
    $("body").append(label, element);        
});

[See it in action]

  • This can handle multiple sets of data
  • As scalability, it can be extended to cover more than just select types.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!