Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing name attribute using jQuery

Tags:

jquery

I've got a jQuery function that attempts to change the id, name and class attribute values of an element.

The id and class change seems to work but for some curious reason, trying to change the name of the element never works.

Here is my code:

$(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) {                  $("#" + id).attr('classname', 'selected');                 $("#" + id).attr('id', 'sel' + rowIndex);                 $("#" + id).attr('name', 'sel' + rowIndex); // this never works                  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);                  $.each(data, function (GetSubCatergories, Category) {                     $('#parent_id').append($("<option></option>").        attr("value", Category.category_id).        text(Category.name));                 });             }          });      } }); });  
like image 299
kevin Avatar asked Apr 26 '10 16:04

kevin


People also ask

How to change name using JQuery?

Approach: Select the HTML element which need to be change. Copy all attributes of previous element in an object. Replace the previous element by new element.

How to change attribute value in HTML using JQuery?

Set multiple attributes and values: $(selector). attr({attribute:value, attribute:value,...})


1 Answers

The name cannot be changed because once you have modified the id, the selector in the subsequent expression (which uses the unmodified id) is selecting nothing :)

$("#" + id).attr('id', 'sel' + rowIndex); $("#" + id).attr('name', 'sel' + rowIndex); // this can't ever work 

Try chaining them together like this, to keep the reference to the current selection:

$("#" + id).attr('id', 'sel' + rowIndex)            .attr('name', 'sel' + rowIndex); 

Alternatively, reorder the statements such that you change the name (and/or whatever else) before changing the id:

$("#" + id).attr('name', 'sel' + rowIndex); $("#" + id).attr('id', 'sel' + rowIndex); 

You can also assign the selection to a variable:

var $el = $("#" + id); $el.attr("id", 'sel' + rowIndex); ... 
like image 100
karim79 Avatar answered Nov 09 '22 16:11

karim79