Currently our dev team uses this pattern, but I can't help but wonder if there is a faster or more html-efficient way of accomplishing the same task. HTML
Solution 1:
This is a function I wrote to do just that. I'm not sure if it's faster than jQuery Templates. It creates and appends the Option elements one at a time, which may be slower than Templates . I suspect that Templates builds the whole HTML string, and then creates the DOM elements all in one shot. That may be a faster. I suppose this function could be adjusted to do the same thing . I've worked with Templates, and I do find that this function is easier to consume for something a simple as populating a Select list, and it fits nicely into my utility.js file.
Update: I updated my function to build the HTML first, and call append() only once. It actually runs much faster now. Thanks for posting this question, it's nice to be able to optimize one's own code.
Consuming the function
var users = [ {id : 1 , name: 'Alice' }, {id : 2 , name: 'Bob' }, {id : 3 , name: 'Cindy' } ]
setSelectOptions($('#selectList' ), users, 'id' , 'name' );
Copy The function code
function setSelectOptions (selectElement, values, valueKey, textKey, defaultValue ) {
if (typeof (selectElement) == "string" ) {
selectElement = $(selectElement);
}
selectElement.empty ();
if (typeof (values) == 'object' ) {
if (values.length ) {
var type = typeof (values[0 ]);
var html = "" ;
if (type == 'object' ) {
var optionElement = null ;
$.each (values, function ( ) {
html += '<option value="' + this [valueKey] + '">' + this [textKey] + '</option>' ;
});
} else {
$.each (values, function ( ) {
var value = this .toString ();
html += '<option value="' + value + '">' + value + '</option>' ;
});
}
selectElement.append (html);
}
if (typeof defaultValue != 'undefined' ) {
selectElement.children ('option[value="' + defaultValue + '"]' ).attr ('selected' , 'selected' );
}
}
return false ;
}
Copy
Post a Comment for "Best Way To Populate Select List With Jquery / Json?"