let say i have a <select id="chat" size="9" />
, i want to add some optgroup and option which will be like this
http://jsfiddle.net/ZP4E9/
with object like this
{friendchat:[{name:"somefriend1",...},{name:"somefriend2",...},
otherchat:[{name:"someother1",...},{name:"someother2",...},
friendrequest:[{name:"somerequest1",...},{name:"somerequest2",...},
sentrequest:[{name:"somesent1",...},{name:"somesent2",...}]
edit: typed input instead of select...
Sample fiddle
You could (need to) use:
document.createElement()
element.appendChild()
element.textContent
, or element.innerHTML
or element.innerText
Having the options object:
var opt = {
friendchat:[
{name:"somefriend1"},
{name:"somefriend2"}
],
otherchat:[
{name:"someother1"},
{name:"someother2"}
],
friendrequest:[
{name:"somerequest1"},
{name:"somerequest2"}
],
sentrequest:[
{name:"somesent1"},
{name:"somesent2"}
]
};
A wrapper to put the select into:
<div id="wrap_sel"></div>
We can add by for example:
/* Build option group.
* @sel : Select element to add group to.
* @lab : Label for option group.
* @opts: Options Array.
* * * * * * * * * * * * * * * * * * * * * * * * * */
function add_optgr(sel, lab, opts) {
var i,
len = opts.length, opt,
gr = document.createElement('OPTGROUP');
gr.label = lab;
for (i = 0; i < len; ++i) {
opt = document.createElement('OPTION');
opt.textContent = opts[i].name;
// Here you most likely also want to set .value
// opt.value = opts[i].value;
gr.appendChild(opt);
}
sel.appendChild(gr);
return gr;
}
/* Build the select.
* @wrap: Container where to add finished product.
* @size: Size attribute for select.
* @opt : Options object.
* * * * * * * * * * * * * * * * * * * * * * * * * */
function build_select(wrap, size, opt) {
var sel = document.createElement('SELECT'),
prop;
size = size || 1;
sel.size = size;
for (prop in opt)
if (opt.hasOwnProperty(prop))
add_optgr(sel, prop, opt[prop]);
wrap.appendChild(sel);
}
/* On DOM ready, build the select. */
build_select(
document.getElementById('wrap_sel'),
9,
opt
);
As commented in code, you would likely want to have a value for the options as well. Giving you options object structure something like:
var opt = {
friendchat:[
{name: "Some Friend 1", value: "friend1"},
{name: "Some Friend 2", value: "friend2"}
],
...
};
Well, how about jQuery ?
http://jsfiddle.net/ZP4E9/2/
var opt = {
friendchat:[
{name:"somefriend1"},
{name:"somefriend2"}
],
otherchat:[
{name:"someother1"},
{name:"someother2"}
],
friendrequest:[
{name:"somerequest1"},
{name:"somerequest2"}
],
sentrequest:[
{name:"somesent1"},
{name:"somesent2"}
]
};
$(function(){
var $select = $('#mySelect');
$.each(opt, function(key, value){
var group = $('<optgroup label="' + key + '" />');
$.each(value, function(){
$('<option />').html(this.name).appendTo(group);
});
group.appendTo($select);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With