JQuery suspicious naming issue
I have a problem with this jQuery function, the part of the function that renames the id, class and name of the dropdown only works for the first dropdown, the subsequent ones don't work, any ideas?
I suspect it might have something to do with the naming convention as in cat.parent_id, but it is required to bind the asp.net mvc model.
$(document).ready(function () {
$("table select").live("change", function () {
var id = $(this).attr('id');
if ($(this).attr('classname') != "selected") {
var rowIndex = $(this).closest('tr').prevAll().length;
$.getJSON("/Category/GetSubCategories/" + $(this).val(), function (data) {
if (data.length > 0) {
//problematic portion
$("#" + id).attr('classname', 'selected');
$("#" + id).attr('name', 'sel' + rowIndex);
$("#" + id).attr('id', 'sel' + rowIndex);
var position = ($('table').get(0));
var tr = position.insertRow(rowIndex + 1);
var td1 = tr.insertCell(-1);
var td2 = tr.insertCell(-1);
td1.appendChild(document.createTextNode('SubCategory'));
var sel = document.createElement("select");
sel.name = 'parent_id';
sel.id = 'parent_id';
sel.setAttribute('class', 'unselected');
td2.appendChild(sel);
$('#parent_id').append($("<option></option>").attr("value", "-1").text("-please select item-"));
$.each(data, function (GetSubCatergories, Category) {
$('#parent_id').append($("<option></option>").
attr("value", Category.category_id).
text(Category.name));
});
sel.name = 'cat.parent_id';
sel.id = 'cat.parent_id';
}
});
}
});
});
+2
a source to share
1 answer
You are trying to set the id of what you selected by id, which might not be a good start.
$("#" + id).attr('id', 'sel' + rowIndex); // Shouldn't do that I think
I think you want to replace this line
var id = $(this).attr('id');
from
var currentDropdown = this;
Then when you want to access it inside getJSON do the following:
$(currentDropdown)
So your problematic part will look like this:
$(currentDropdown).attr('classname', 'selected');
$(currentDropdown).attr('name', 'sel' + rowIndex);
$(currentDropdown).attr('id', 'sel' + rowIndex);
+1
a source to share