Problem with Events
Problem with Events
Hi there, I'm new to jQuery but I can't seem to find an example for what I'm doing. At least any examples I've found don't have this problem.
On a click event of a jqGrid row I'm loading two <ul> lists with Ajax. I'm trying to bind click events to each <li> so they call a function that will put them in the other list. It's your basic "Assigned Values/Available Values" paradigm. Values are states assigned to vendors in this example.
It works but when the click events are bound to the <li> elements, the events fire so the states go back and forth endlessly. I can't find any reference to events firing automatically like that. Anyone see what I'm doing wrong?
<ul id='ulAssigned'></ul>
<ul id='ulUnassigned'></ul>
<script type="text/javascript">
function getDetails(row_id) {
// List of Assigned States
$.getJSON('<%= Url.Action("GetAssigned", "Vendors") %>' + '?vendorID=' + row_id, null, function (data) {
for (i = 0; i < data.length; i++) {
var stateCode = data[i].StateCode;
var stateName = data[i].Name;
var vendorID = row_id;
var itemSelector = "#li_" + stateCode;
li = "<li id='li_" + stateCode + "'>" + stateName + "</li>";
$(itemSelector).unbind("click");
$(itemSelector).click(unassignState(vendorID, stateCode));
$("#ulAssigned").append(li);
}
});
// List of Unassigned States
$.getJSON('<%= Url.Action("GetUnassigned", "Vendors") %>' + '?vendorID=' + row_id, null, function (data) {
for (i = 0; i < data.length; i++) {
var stateCode = data[i].StateCode;
var stateName = data[i].Name;
var vendorID = row_id.toString();
var itemSelector = "#li_" + stateCode;
li = "<li id='li_" + stateCode + "'" + stateName + "</li>";
$(itemSelector).unbind("click");
$(itemSelector).click(assignState(vendorID, stateCode));
$("#ulUnassigned").append(li);
}
});
}
// Assigns the State to the Vendor, moves the <li> and reassigns the event
function assignState(vendorID, stateCode) {
var itemSelector = "#li_" + stateCode;
$(itemSelector).fadeOut();
$.ajax({
url: '<%= Url.Action("AssignState", "Vendors") %>' + "?vendorID=" + vendorID + "&stateCode=" + stateCode,
type: "GET",
success: function (html) {
$("#ulAssigned").append($(itemSelector));
$(itemSelector).unbind("click");
$(itemSelector).click(unassignState(vendorID, stateCode));
$(itemSelector).fadeIn();
},
error: function (xhr, ajaxOptions, thrownError) {
$(itemSelector).fadeIn();
}
});
}
// Unassigns the State to the Vendor, moves the <li> and reassigns the event
function unassignState(vendorID, stateCode) {
var itemSelector = "#li_" + stateCode;
$(itemSelector).fadeOut();
$.ajax({
url: '<%= Url.Action("UnassignState", "Vendors") %>' + "?vendorID=" + vendorID + "&stateCode=" + stateCode,
type: "GET",
success: function (html) {
$(itemSelector).unbind("click");
$(itemSelector).click(unassignState(vendorID, stateCode));
$("#ulUnassigned").append($(itemSelector));
$(itemSelector).fadeIn();
},
error: function (xhr, ajaxOptions, thrownError) {
$(itemSelector).fadeIn();
}
});
}
</script>