views:

710

answers:

4

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.

+3  A: 

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");
Gumbo
could have tried resolving it the jquery way. nevertheless +1 for spotting the mistake.
thephpdeveloper
well spotted, I'll revisit the code. These responses are a great help to people like me who work alone.
Alan C
A: 

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.

GSto
id*= means it should only contain that value, so you don't have to prepend anyhting...
Nicky De Maeyer
ah. missed the * there.
GSto
A: 

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.

Kieron
+1  A: 

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

Matt Ball