Hey I found this function online and it works fine if I use it by itself, but the rest of my document has all jQuery functions and I'd like this one to be in jQuery as well.
I also get a few errors when mixing prototype and jQuery.
Here is the function:
function updateCommodityProduct(e) {
// The response comes back as a bunch-o-JSON
var objects = eval("(" + e.responseText + ")") // evaluate JSON
if (objects) {
var rselect = document.getElementById('commodityProduct')
// Clear all previous options
var l = rselect.length
while (l > 0) {
l--
rselect.remove(l)
}
// Rebuild the select
for (var i=0; i < objects.length; i++) {
var object = objects[i]
var opt = document.createElement('option');
opt.text = object.enDescription
opt.value = object.productCode
try {
rselect.add(opt, null) // standards compliant; doesn't work in IE
}
catch(ex) {
rselect.add(opt) // IE only
}
}
}
}
Thanks in advance!!
UPDATE:
Here is where the function is being used:
I'm using it with Grails, but g:select is almost the same thing as a select I can also use a select if that's an option too.
(Here is some information on g:select and properties, pretty simple, http://www.grails.org/doc/1.0.x/ref/Tags/select.html )
<td valign="top"><form id="selectForm">
<b>GROUP:</b>
<g:select id="productGroups" optionKey="groupCode" name="getAllProductGroups2" from="${getAllProductGroups}" optionValue="enDescription" onchange="${remoteFunction(controller:'comodity', action:'ajaxGetCommodities', params:'\'groupCode=\' + escape(this.value) ', onComplete:'updateCommodityProduct(e)')}" style="width:220px" />
</br>
<b>COMMODITY:</b>
<g:select name="commodityProduct" id="commodityProduct" style="width:220px">
</g:select></form></td>
Thanks again!!
This is a bit shorter in jQuery, like this:
function updateCommodityProduct(objects) {
if (!objects) return;
var select = $('#commodityProduct').empty();
$.each(objects, function(i, o) {
$("<option />", { text: o.enDescription, value: o.productCode })
.appendTo(select);
});
}
Notice this version takes the objects already, just change your $.ajax()
dataType
to "json"
and it'll already be an object at this point. You'd use this as your success
callback directly, for example:
$.ajax({
//....options...
success: updateCommodityProduct
});