views:

63

answers:

2

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!!

+2  A: 

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
});
Nick Craver
Where does the $.ajax({ --- } go?
fgualda87
@fgualda87 - You're using this code somewhere, as the result of an AJAX request...where is that?
Nick Craver
I'm using it on an onChange of a <select>
fgualda87
@fgualda87 - An `onChange` wouldn't be passing back an XmlHttpRequest, I would need to see where you're using it.
Nick Craver
When it changes it should go to the database and load another <select> with certain values, but depending on the text and value it should load certain elements on the other one.
fgualda87
Ok let me update with some code.
fgualda87
Ok, code updated. It works fine if I do it separately using the prototype function, but since I'm using jquery it doesn't work when I mix both of them. Also I don't want to have half prototype half jQuery, I prefer all jquery. Thanks!!
fgualda87
Maybe is the `onchange="${remoteFunction(controller:'comodity', action:'ajaxGetCommodities', params:'\'groupCode=\' + escape(this.value) ', onComplete:'updateCommodityProduct(e)')}"` where I'm making the mistake, calling the function like that, is that the right way??
fgualda87
+1  A: 

Part of this code doesn't make sense. Either it was modified from the original, or it was wrong to begin with.

Anyway, I'm guessing at the intention of the code, but give this a try:

function updateCommodityProduct(e) {
    // The response comes back as a bunch-o-JSON
    var objects = eval("(" + e.responseText + ")")  // evaluate JSON

    if (objects) {
        var $rselect = $('#commodityProduct').empty();
        $.each( objects, function(i,val) {
            $('<option/>', {text:val.enDescription,value:val.productCode})
                          .appendTo($rselect);
        });
    }
}

EDIT:

If productGroups is the <select> that should trigger the event, then you could do something like this:

    // run the code on DOM ready
$(function() {

       // attach a change() handler to the productGroups element
    $('#productGroups').change(function() {

         // Retrieve the selected value of the <select> element
        var value = $(this).val();

         // You'll need to send the selected value to the server.

        $.ajax({
            url: '/path/to/resource', // your server url here
            dataType: 'json',         // anticipate JSON response from server
            success: function( resp ) {
                // trigger an alert() to show that response was received
                alert( resp );

                if (resp) {
                    var $rselect = $('#commodityProduct').empty();
                    $.each( resp, function(i,val) {
                        $('<option/>', {text:val.enDescription, value:val.productCode})
                              .appendTo($rselect);
                    });
                }
            }
        });
    });
});
patrick dw
Is not working right S: nothing happens
fgualda87
@fgualda87 - This is just a function. I would need to see how it is being called to know what is going on. In your question you say *"g:select is almost the same thing as a select"*. Looking at the docs, it seems as though they *are* the same thing. The docs state: *"Purpose: Helper tag for creating HTML selects."* Is that right? Are you getting a typical `<select>` element on the page? I'll give you a hand, but I'll probably need to ask a few more questions.
patrick dw
@patrick - I do get a typical `<select>` if you see the source of the page, but they have different properties. They can be treated the same way though.
fgualda87
@fgualda87 - Ok, so how are you making the AJAX request? Are you using jQuery's `$.ajax()` method? Could you post that code in your question?
patrick dw
@patrick No I'm not using the $.ajax() I don't know how to use it or where to put it
fgualda87
@fgualda87 - The code you posted in your question appears to be a *callback* to an AJAX request. An AJAX request is sent to the server, and when a response is received, a callback typically runs. There can be different callbacks for different situations. Yours looks like it should run when a *successful* response is received. But first you need to make a request. Do you know the URL that should be sent to the server (your Grails application) to request the data?
patrick dw
Yes, but I don't know if it's safe to post it. Where should the `$.ajax()` method go?
fgualda87
@fgualda87 - No, you don't need to post it. I just need to find out what you have/don't have. With regard to where `$.agax()` should go, that will depend upon *when* you want it called. In other words, what should trigger the request? The page load? A click somewhere on the page? Or some other event?
patrick dw
Well the event is to load some data on on a combobox, depending on another combobox, and getting all that data from a DB. So I think it should be either the onChange of the first combobox, OR the page load.
fgualda87
@fgualda87 - I updated my answer. There are probably some missing details since I don't know exactly what your server is expecting to get, but this should take you closer.
patrick dw
@fgualda87 - So did this work, or not?
patrick dw
I'm having problems with the database. I will let you know as soon as they fix it. Thanks for worrying though!
fgualda87
Here is where it gets called. It might be helpful. `<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" />`
fgualda87
Notice that updateCommodityProduct is the name of the method
fgualda87