Reputation: 29
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.
Upvotes: 0
Views: 8532
Reputation: 359826
You have to be careful about escaping weird characters in your IDs. See the jQuery FAQ for more.
Upvotes: 1
Reputation: 27107
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.
Upvotes: 0
Reputation: 42350
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.
Upvotes: 0
Reputation: 655239
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");
Upvotes: 8