Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: find and replace of attribute values

Tags:

I am having difficulty performing a find and replace of attribute values.

Consider this html:

<tr id="rules[0]">     <td>         <input id="rules0.isActive1" name="rules[0].isActive" type="checkbox" value="true"/><input type="hidden" name="_rules[0].isActive" value="on"/>     </td>     <td>         <select id="rules0.leftCondition.name" name="rules[0].leftCondition.name">             ...         </select>     </td> 

I am looking to update each 's name attribute with the appropriate count e.g. rules[0].isActive is updated to rules[10].isActive

I am using this JQuery snippet:

$(newRow).find('[id*="rules"]').each(function(){     // Update the 'rules[0]' part of the name attribute to contain the latest count      this.name.replace('rules\[0\]','rules\[$count\]'); });  

where newRow is a variable holding the entire block and count holds the latest counter value. However, when I debug this code it seems that "this.name" is undefined.

Where am I going wrong here?

Thanks

like image 645
DJ180 Avatar asked Jan 04 '12 15:01

DJ180


People also ask

Which jQuery function is used to change the value of any attribute?

The jQuery attr() method is used to get the value of an attribute. It can also be used to change the value.

What is ATTR jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How get data attribute value in jQuery?

You can use this jquery data() syntax for get data-id attribute value. $("selector"). data("textval"); You can use this jquery data() syntax for get data-textval attribute value.

How check attribute is present or not in jQuery?

Using jQuery The idea is to use the . attr() method, which returns the attribute's value for an element if it is present and returns undefined if the attribute doesn't exist.


1 Answers

To update attribute of element you should use the .attr function. Also, when using this in jQuery context you must use $(this) syntax. If I understand your intentions so it should be something like that:

$(newRow).find('[id*="rules"]').each(function(){     // Update the 'rules[0]' part of the name attribute to contain the latest count      $(this).attr('name',$(this).attr('name').replace('rules\[0\]','rules\[$count\]')); });  
like image 88
kaz Avatar answered Sep 23 '22 08:09

kaz