0

can someone explain why this jquery selector is not working, I've worked around the issue but for my sanity would like to know what I've got wrong

I have a form with multiple textareas, each gets an id like f_id_DSC000001.JPG where the last part is a photograph number, the textarea has an onblur event that uses post to send its contents and update a database table, a json response comes back. All of that works fine, I can see the results using Firebug, there are no problems there.

The DSC000001.JPG part of the id gets passed back in the json response as confirmation, then I want to change the class of the textarea to show the state of the update.

When I do this

var textarea_selector="#f_id_"+res_data.image_filename;
$(textarea_selector).removeClass("kw-class");
$(textarea_selector).addClass("update-failed");

the class does not change, but if I do this

$("textarea[id*='"+res_data.image_filename+"']").removeClass("kw-class");
                  $("textarea[id*='"+res_data.image_filename+"']").addClass("update-done");

it works fine.

I'm not a javascript / jquery expert :-( so a basic explanation is what I would really appreciate.

4 Answers 4

8

You have a dot in your ID. And that’s interpreted as a class selector:

#f_id_DSC000001.JPG
\_____________/\__/
 id             class

But this should work:

var textarea_element = document.getElementById("f_id_"+res_data.image_filename);
$(textarea_element).removeClass("kw-class").addClass("update-failed");

Or this:

var textarea_id = "f_id_"+res_data.image_filename;
$("[id="+textarea_id+"]").removeClass("kw-class").addClass("update-failed");
Sign up to request clarification or add additional context in comments.

2 Comments

could have tried resolving it the jquery way. nevertheless +1 for spotting the mistake.
well spotted, I'll revisit the code. These responses are a great help to people like me who work alone.
1

You have to be careful about escaping weird characters in your IDs. See the jQuery FAQ for more.

Comments

0

it looks like you are calling two different ids. why are you appending "#f_id" in the first example? you should just be able to append '#' to the id of an element and select it just fine.

1 Comment

id*= means it should only contain that value, so you don't have to prepend anyhting...
0

Try:

var textarea = $("textarea[id*='"+res_data.image_filename+"']");
textarea.removeClass("kw-class");
textarea.addClass("update-failed");

You're not constructing the selector the same as the example in your post, which is why it's failing. This solution you're only doing the select once.

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.