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);
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)
}
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);
});
- This can handle multiple sets of data
- As scalability, it can be extended to cover more than just select types.