简体   繁体   中英

Dynamically change element name in jquery

The following is my element id and I want to update it dynamically.

invoice[46][ap_details][4][ap_header_id]  

I want to update only second number, ie [4] , like this:

invoice[46][ap_details][5][ap_header_id]

I am using below code which is updating both the values.

var strNewName = $(this).attr('name').replace(/\[\d+\]/g, function(strName) {
    strName = strName.replace(/[\[\]']+/g, '');
    var intNumber = parseInt(strName) + 1;
    return '[' + intNumber + ']';
});

Any help would be appreciated.

Using this regex /((\\w)+)(\\[\\d+\\])(\\[(\\w)+\\])(\\[\\d+\\])(\\[(\\w)+\\])/gi you can construct the string back and change your integer.

var match = /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi.exec(youString);
//group 6 is your digit.
var newId = parseInt(match[6].replace("\[\]", "")) + 1;
var newString = match[1] + match[3] + match[4] + "[" + newId + "]" + match[7];

Here is a fiddle with the answer https://jsfiddle.net/gzfud9vc/

 var strName = "invoice[46][ap_details][4][ap_header_id]"; var parts = strName.split('['); parts[3] = parts[3].replace(/^\\d+/, n => +n + 1); var strNewName = parts.join('['); console.log(strNewName); 

If you don't want to use arrow functions replace this line:

parts[3] = parts[3].replace(/^\d+/, n => +n + 1);

with this:

parts[3] = parts[3].replace(/^\d+/, function(n) { return +n + 1; });

Explanation:

split will return an array like this:

[
  "invoice",
  "46]",             // parts[1] to change this
  "ap_details]",
  "4]",              // parts[3] to change this (and so on, you do the math)
  "ap_header_id]"
]

The /^\\d+/ will match any number at the begining (no need for the g modifier).

Replace with +n + 1 not n + 1 because n is a string, you have to force the interpretter to use it as a number or otherwise this "4" + 1 will result to this "41" .

Then after you change what you want, join the parts using join with the same character you used for splitting ( [ ).

Maybe dont use regex to build your element id. You can do its as follows as well:

 var id = 5 var name = "invoice[46][ap_details]["; name += id; name += "][ap_header_id]"; var toReplace = "invoice[46][ap_details][~~id~~][ap_header_id]" var replaced = toReplace.replace(/~~id~~/g, id); console.log(name); console.log(replaced); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM