开发者

manipulating dynamically created form elements without losing their values with jQuery

开发者 https://www.devze.com 2023-02-12 01:49 出处:网络
I want to do a search and replace on a complex bit of dynamically created form. It\'s as simple as finding all the instances of one string and replacing them with another, made more complicated by the

I want to do a search and replace on a complex bit of dynamically created form. It's as simple as finding all the instances of one string and replacing them with another, made more complicated by the fact there are 11 instances per bit of form and make up only parts of various attributes.

Examples of the kind of thing I'm working with (it's the '001' bit I'm searching and replacing):

<div id="step_title:001|title">
<label for="step_title:001|title|field">
<input id="step_title:001|title|field" name="step_title:001|title|field"/>

I had thought something like this would do the trick:

$(this).html($(this).html().replace('old string', 'new string'));

However because the bit of form is dynamically added the form data is lost every time I perform this action. I tried using the .clone() function which seems to preserve the data, but that doesn't allow you to manipulate the object. I also tried performing the search and replace directly onto the containing 开发者_开发问答object, but I guess .replace() only works on strings.


Can you just update the attributes instead?

$('div, label, input').each(
    function() {
        var _this = $(this);
        _this.attr('id', _this.attr('id').replace('old string', 'new string'));
        _this.attr('for', _this.attr('id').replace('old string', 'new string'));
        _this.attr('name', _this.attr('id').replace('old string', 'new string'));
    }
);

Might be a bit longwinded...

0

精彩评论

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

关注公众号