3

I have a few select elements on my page and i want to remove a part of the name.

Their name look something like this:

ctl02$fieldname

The part that i want to remove is: ctl02$. So that it leaves me with fieldname only.

That part that i want to remove always starts with ctl then a two digit number ending with a $.

I tried it with the following code, but that didn't do the trick:

$(".elements select").each(function() {
    this.setAttribute("name", this.getAttribute("name").replace(/ctl([0-9]+)\$$/, ""));
});

Anyone any idea how i can do this?

Here's a demo: http://tinkerbin.com/Klvx5qQF

2
  • Those look awfully similar to the names generated by asp.net web-forms. If you do use asp.net 4.0 or later, try using the ClientIDMode to model the ID's on the server, with no need of client side mangling. Commented Jan 30, 2013 at 10:04
  • @SWeko Thanks for the advice. But unfortunately i'm using ASP.NET 3.5. So those are indeed generated names. Commented Jan 30, 2013 at 11:01

3 Answers 3

4

Just an error in the regex. I don't know why you doubled the $, a $ at the end of a regex has a specific meaning that isn't what you want.

Here's the fixed version :

$(".elements select").each(function() {
    this.setAttribute("name", this.getAttribute("name").
       replace(/ctl[0-9]+\$/, ""));
});

You don't need to capture anything, that's why I also removed the parenthesis.

If you want to be sure to remove the ctl thing only when it's at the start of the name, you may change the regex to /^ctl[0-9]+\$/.

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

Comments

4

I guess there is no need in regex here:

$(".elements select").attr("name", function(i, attr) {
    return attr.substring(attr.indexOf("$") + 1);
});

Comments

0

use this :

$(function() {
    $("select").each(function() {
        var name = $(this).attr("name");

        $(this).attr("name", name.replace(/(ctl[0-9]+)/g, ""));

    });
});

see demo : link

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.