开发者

dynamically renaming form elements with JavaScript

开发者 https://www.devze.com 2023-04-05 04:58 出处:网络
I have a table inside a form, which is populated with various input boxes. I have written various JavaScript functions that will allow the user to add or remove a row from the table, and will also dyn

I have a table inside a form, which is populated with various input boxes. I have written various JavaScript functions that will allow the user to add or remove a row from the table, and will also dynamically rename the element names that come after where the user has entered the row (if that makes sense - hopefully my code will explain what I'm trying to do).

This works in IE9, Firefox and Chrome, but not in IE7 (which a lot of people in my organization who are still on XP currently use).

The code isn't the most elegant thing I've ever written, but I need to fix this before demoing it in front of people tomorrow! (So I'm willing to consider anything, even if it's a quick and dirty fix at this point!)

Thanks!

for (var e = 0; e < editForm.elements.length; e++) {
    // Increment 'add row' buttons so that they add underneath the correct row
    if (editForm.elements[e].name.length >= 4) {
        if (editForm.elements[e].name.substr(0, 4) == 'add_') {
            stringPos = editForm.elements[e].name.indexOf('_');
            currentQuestionNumber = editForm.elements[e].name.substr(stringPos + 1);
            if (currentQuestionNumber > pos) {
                editForm.elements[e].name = 'add_' + (parseInt(currentQuestionNumber) + 1);
                editForm.elements[e].id = 'add_' + (parseInt(currentQuestionNumber) + 1);
                editF开发者_开发问答orm.elements[e].setAttribute("onclick", "addRow(" + (parseInt(currentQuestionNumber) + 1) + ");");
            }
        }
    }

In place of...

editForm.elements[e].name = 'add_' + (parseInt(currentQuestionNumber) + 1);

...I have also used...

editForm.elements[e].setAttribute("name", "add_" + (parseInt(currentQuestionNumber) + 1));

...but this doesn't work in IE7 either. Any help appreciated.


In case the elements you're changing names have been dynamically created, you may be hitting an IE6/7 bug. There's a pointer to a possible workaround to the setAttribute bug on the Web Bug Track blog. You may also find the answers to "Changing name attr of cloned input element in jQuery doesn't work in IE6/7" useful.

0

精彩评论

暂无评论...
验证码 换一张
取 消