jquery - DOM traversal question
- by David
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;
});