I’m having a problem with this jQuery function, the portion of the function that renames the id, class and name of the dropdown only works for the first dropdown, subsequent ones do not work, any ideas?
I suspect it may have something to do with naming convention as in cat.parent_id but it is required for asp.net mvc model binding.
$(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';
}
});
}
});
});
You’re trying to set the Id of something that you selected by ID that can’t be good for a start.
I think you want to replace this line
with
Then when you want to access it inside getJSON do this:
So your problematic portion would now look like: