2

i need to modify multiple IDs, classes and names of a div, span, select and other elements.

i clone the html from the last row i have in a table, like

var num     = $('.clonedLighting').length; // num of current rows
var newNum  = new Number(num + 1);      // the numeric ID of the new input field being added

// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#inputlighting' + num).clone().prop('id', 'inputlighting' + newNum);

Then in the next step i modify the cloned IDs like

newElem.children('td').children('label.prod_item').prop('for', 'appliancetextfield' + newNum);
newElem.children('td').children('select.prod_item').prop('id', 'appliancetextfield' + newNum).prop('name', 'appliancetextfield' + newNum).prop('value', '');

which is working OK. however, the appliancetextfield sections now has many more elements. I would like to replace all names, classes and IDs that contain

'appliancetextfield'+num

with

'appliancetextfield'+newNum

instead of doing it for every element. is this possible? how?

to clarify: the IDs, classes or names would look like

appliancetextfield4
appliancetextfield4_title
appliancetextfield4_titleText
appliancetextfield4_msdd

and should turn into

appliancetextfield5
appliancetextfield5_title
appliancetextfield5_titleText
appliancetextfield5_msdd

at this point it looks like the number will only ever be single digit, but one day may have to go up to 10 or higher. Thanks for any input.

EDIT: Trying to implement the below suggestions and lots of googling: I now have:

var num     = $('.clonedLighting').length; // current rows
var newNum  = new Number(num + 1); 

$('#inputlighting' + num).clone().prop('id', function(index, id) {
    return id.replace(/(appliance.*)\d\d?(.*)/g, "$1" + newNum + "$2");
}).insertAfter($('#inputlighting' + num));

it looks like the right track but the regular expression and/or the back-referencing doesn't work.

4

1 回答 1

0

我想我明白了:

        //newElem is the newly cloned object
    newElem.find('[id^=appliance]').prop('id', function(index, id) {
            return id.replace(/(appliance.*)\d\d?(.*)/g,"$1" +newNum+ "$2");
    });
    newElem.find('[for^=appliance]').prop('for', function(index, id) {
            return id.replace(/(appliance.*)\d\d?(.*)/g,"$1" +newNum+ "$2");
    });
    newElem.find('[name^=appliance]').prop('name', function(index, id) {
            return id.replace(/(appliance.*)\d\d?(.*)/g,"$1" +newNum+ "$2");
    });

感谢您的帮助。

于 2013-04-24T14:57:46.240 回答