1

I have an script that when click a button do many things and also rename some elements, so at first I use first script and I see sometimes work, sometimes not, so change it to second script and all time worked perfectly, but there is a question. is this two scripts do same? what is the difference, rather than all of my script I just replace first one with second one.

This is first script

$(CloneTarget).find(':input[name="' + MainName + '"]').attr('name', NewSelectName);

And second one:

$(CloneTarget).find(':input').each(function () {
    if ($(this).attr('name') == MainName) {
        $(this).attr('name', NewSelectName);
    }
});

Where is the problem with first one?

Edit

Also I use this:

    $(CloneTarget).find(':input[id="' + MainId + '"]').attr('id', NewSelectId);

And every thing worked fine I am really confused here, I must mention MainName and MainId are so similar like: MainName = Model.Phones[0] and MainId = Model_Phones[0] is the difference is about . character or any other things?

4
  • what "does not work" in the first script? Commented May 17, 2012 at 6:03
  • Can you give the HTML part as well, just to be clear. Commented May 17, 2012 at 6:04
  • @Saeid, the . character may be mistaken for the start of a class selector, however it doesn't seem to be the case as of jQuery 1.7. Are you using an earlier version of the library? Commented May 17, 2012 at 6:24
  • @FrédéricHamidi Yes. I use jQuery JavaScript Library v1.7.1 Commented May 17, 2012 at 6:26

1 Answer 1

7

Yes, there is a difference. Your second code snippet performs a string comparison between the element's name attribute and the value of MainName. The first one directly injects the value of MainName into an Attribute Equals selector.

Therefore, the first snippet will fail if MainName happens to contain:

  • a single quote character ',
  • a double quote character ",
  • a character that requires escaping in selectors, such as [ or \.
Sign up to request clarification or add additional context in comments.

3 Comments

That's awesome, I think my MainName is similar of your description, but I use it with Id without any problem, I update question
But you aren't supposed to give names with those quotes and escaping characters as Input names. That's the first thing.
@ngen, in theory, yes, but PHP developers sometimes name the check boxes or radio buttons in a group something[], in order for the server-side code to receive an array containing the values submitted for these elements.

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.