1

I have the following code:

​<div id="container">
 <input type="text" name="a1" id="a1">
 <input type="text" name="a2" id="a2">
​</div>​​​​​​​​​​​​​​​​

And I want to replace all instance of the text "a" to "b" for the id and name property for all the element inside the div id="container"

so the new code should be like this:

​<div id="container">
 <input type="text" name="b1" id="b1">
 <input type="text" name="b2" id="b2">
​</div>​​​​​​​​​​​​​​​​

I just can't seem to be able to make it work using the javascript replace().

1
  • 4
    Show us the code you've tried already. Also, you clearly don't want to replace all a with b because you'd end up with markup like <input type="text" nbme="b1" id="b1">. So what are you actually trying to do? Commented Mar 20, 2012 at 13:42

4 Answers 4

6
$('#container input').each(function(){ // Loop through all inputs
    this.name = this.name.replace('a', 'b');  // Replace name
    this.id = this.id.replace('a', 'b');  // Replace ID
});

DEMO: http://jsfiddle.net/G3vCf/

Sign up to request clarification or add additional context in comments.

Comments

1
$('#a1').attr('name', 'b1').attr('id', 'b1');
$('#a2').attr('name', 'b2').attr('id', 'b2');

Comments

0
$("#container").children("input").each(function() {
    var name = $(this).attr("name");
    var id = $(this).attr("id");

    name = name.replace(/a/g, "b");
    id = id.replace(/a/g, "b");

    $(this).attr("name", name);
    $(this).attr("id", id);
});

Comments

0

Here

 $(function(){
    var html =$('#container').html().replace(/a/g,'b');
    $('#container').html(html);​
});

Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.