1

I need to replace ||| from all the input fields using jquery. But it is only replacing the first item. I need to use regex but I don't know how to add that to the string.

$(document).ready(function() {
    $("#layerPaper").children("div").each(function() {
        $val = $(this).children('input:text');
        $val.val($val.val().replace('|||', '\"'));
    });
}); 

Thanks.

1
  • There are some different valid interpretations of your question. What do you mean by "it is only replacing the first item"? Do you mean that each input may have more than one |||? Or does it refer to the fact that in each <div> element you're only using the value of the first <input> element.? Commented Feb 14, 2011 at 23:38

3 Answers 3

4

If you mean there are multiple instances of '|||' in an element then the replace you want is:

replace(/\|\|\|/g, '\"')); 
Sign up to request clarification or add additional context in comments.

2 Comments

/\|{3}/g, too. (Same number of characters, but arguably more legible. ;-)
@Brad, you're right of course, for only a few characters I prefer to show each one, but if there are say more than 5, or if, like here, the character has to be escaped, the "{n}" format is more legible.
3
$("#layerPaper > div > input:text").val(function(i,val){ 
    return val.replace('|||', '\"');
});

5 Comments

Thanks @Brad. jQuery sure has some nice tricks for shortening code.
The code was replacing the ||| with the string function(i,val){ return val.replace('|||', '\"'); Please let me know what is wrong
@dotnetrocks: That's very strange. What version of jQuery are you using? To pass a function, you'll need jQuery 1.4 or later.
I am using the older version ver 1.3.Thanks for correcting that.I will try it using the latest ver.
@dotnetrocks: You're welcome. I think I misunderstood your question initially. I didn't realize you potentially had more than one ||| in an <input> element. The regex solution @Neil gave (or the comment from Brad below his answer) is the way to go.
0

You don't need regex, I think your problem lies in the following:

$val.val($val.val().replace('|||', '\"'));

The .val() function only works on the first element found. You can switch this by using $.each though, fairly simply:

$(this).children('input:text').each(function(i,e){
  $(e).val($(e).val().replace('|||','"'));
});

2 Comments

Using a function callback would be even nicer.
@lonesomeday: I agree, but just want showing where the error was and how to solve. Wasn't going too deeply in to refactoring. Besides, @patrickdw did so for me. ;-)

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.