Update I guess I was to quick to assume voodoo jquery mystery. I noticed I do use the "username" Id twice and that is the problem. the second username id was added to the page through html code that was injected to the page from php, so I couldn't see it in the source at first..
I'm writing this client side validation jquery code:
username = $("#username").val();
if (username.length < 5 || username.length > 15 || !username_regex.test(username)) {
error += "invalid username\n";
$(this).find("label[for='username']").css("color", "red");
$("#username").css("background-color", "#ffc9c9").css("border-color", "red"); //this doesn't work
// $("input[id='username']").css("background-color", "#ffc9c9").css("border-color", "red"); //this works
}
and the html:
<p><label for="username">Username</label><input id="username" type="text" name="username"/></p>
I have several more jquery/html blocks, exactly the same as these above, for password, email, first name etc..
this validation code is part of onsubmit handler and all of the other blocks are working fine: when a field is not met with the validation criteria, the color of it's label turns red and the background color of it's input field turns to #ffc9c9.
the problem is in the username - it's label does turns red, but it's input field does not turns #ffc9c9. I don't see any reason for it not to work, I use the same line:
$("#*input_field_id*").css("background-color", "#ffc9c9").css("border-color", "red");
for every one of the other blocks and it works fine for them.
also see that the commented line:
$("input[id='username']").css("background-color", "#ffc9c9").css("border-color", "red");
does work and solves my need. but it doesn't solves the mystery and I'm trying to figure out why don't the line above work. also notice that I have debugged with firebug and got expected results, for example:
$("#username").attr("name"); // = username, as expected
It comes down to this: why $("input[id='username']") works when I try to change it's css but $("#username") won't ?
That's because IDs must be unique and ID selector only selects the first element with a specific ID, you should use classes instead. You will get the same result by using .getElementById() method of the document object, this is the expected behavior. Attribute selectors work in a different way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With