Bind javascript array or object to html drop down in Jquery

So when we are in developing we have to populate dropdown box with javascript objects. Some times we have to write more dirty codes to do that.

I am using following Jquery function to populate dropdown box with javascript array or object.


//element=> html select element id,
//source=> javascript array
//showDefault=> show default --None-- : optional
//defIndex=> default selected index : optional
function bindCombo(element, source, showDefault, defIndex) {
var k = (typeof element == "string") ? $("#" + element)[0] : element[0];
k.options.length = 0; var r = 0, j = source.length;
if (showDefault) { k.options[0] = new Option("--None--", "-1"); r = 1; }
if (j > 0) {
if (typeof source[0] == "object") { for (var i = 0; i < j; i++) { k.options[i + r] = new Option(source[i].Value, source[i].Id); }; }
else { for (var i = 0; i < j; i++) { k.options[i + r] = new Option(source[i], source[i]); }; }
if (defIndex) $(k).val(defIndex);
}
}

So if we want to bind following array to drop downbox simply we can add html attribute as below and call the above function

<select id=”test”></select> 


<b>var arr = ["one","two"];</b>

<b>bindCombo('test',arr,false,false)</b>

Now it will be populated.

More over we can bind list of following object

 function Pair(Id, Value) {
this.Id = Id;
this.Value = Value;
   }
var arr=[];
arr.push(new Pair(1,first));
arr.push(new Pair(2,second));

bindCombo('test',arr,false,false)

Further we can provide whether to show default “–None–” or set selected index using ending two parameters in function. Just only pass true or false.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s