jquery - DOM traversal question

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2010-04-25T18:11:31Z Indexed on 2010/04/25 18:13 UTC
Read the original article Hit count: 173

Filed under:

Hi,

Basically what I have here is a button that adds a new list item to an unordered list. Within this list item is a dropdown box (.formSelector) that when changed triggers an ajax call to get the values for another dropdown box (.fieldSelector) in the same list item.

The problem is on this line:

$(this).closest(".fieldSelector").append(

If I change it to

$(".fieldSelector").append(

the second box updates correctly. The problem with this is that when I have multiple list items it updates every dropdown box on the page with the class fieldSelector, which is undesirable. How can I traverse the DOM to just pick the fieldSelector in the current list item? Any help is greatly appreciated.

Complete code:

$("button", "#newReportElement").click(function() { 
        $("#reportElements").append("<li class=\"ui-state-default\"> <span class=\"test ui-icon ui-icon-arrowthick-2-n-s \"></span><span class=\"ui-icon ui-icon-trash deleteRange \"></span> <select name=\"form[]\" class=\"formSelector\"><? foreach ($forms->result() as $row) { echo "<option value='$row->formId'>$row->name</option>"; }?></select><select class=\"fieldSelector\" name=\"field[]\"></select></li>");                                   
        $(".deleteRange").button(); 
        $('.formSelector').change(function() { 
            var id = $(this).val();     
            var url = "<? echo site_url("report/formfields");?>" + "/" + id;   
            var atext = "ids:"; 

            $.getJSON(url,
                function(data){
                  $.each(data.items, function(i,item){

                    $(this).closest(".fieldSelector").append(
                            $('<option></option>').val(item.formId).html(item.formLabel)
                        );
                  });
                });    

        });
        return false; 
    });

© Stack Overflow or respective owner

Related posts about jQuery