3

I am trying to write line of jquery that finds an input that has a class that begins with "a\d" (the letter a and a number) and replace the number with another number.

This is what I have tried, does anyone notice why this would not work?

$('form').find('input[class^="a\d"]').replace(/a\d+/,'a22');

Please note: this is one line out of many, I have extracted this line because it is where I am having trouble.

1
  • I don't think the 'attribute begins with' selector works with regular expressions. The documentation states that it"Selects elements that have the specified attribute with a value beginning exactly with a given string." Commented Jan 5, 2011 at 16:47

2 Answers 2

11

You'll need to do it more like this:

$('form').find('input[class^="a"]').attr('class', function(i,cls) {
    if( /a\d/.test( cls ) ) {
        return cls.replace(/a\d+/,'a22');
    }
});

When using .attr() to set the class (or any attribute), you can pass it a function which has 2 parameters. The i is the current index in the iteration. The cls is the current value of class.

The return value will be used to update the class. If nothing is returned, nothing will be changed.

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

1 Comment

Brilliant. Thank you! This works perfectly. I will use this method often!
0

Try this

var regExp = /(a\d+)(.*)?/;
$('form').find('input[class^="a"]').each(
    function()
    {
        var el = this;
        var className = el.replace(regExp, "a22$2");
        el.className = className;
    }
);

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.