Why does $ ("input [id = 'username']") work and $ ("# username") will not?

Update Probably I should have quickly accepted the secret of voodoo-jquery. I noticed that I use the username identifier twice, and this is the problem. the second username id was added to the page via the html code that was added to the page with php, so I could not see it in the source at first.

I am writing this jQuery code for client side validation:

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 html:

  <p><label for="username">Username</label><input id="username" type="text" name="username"/></p>

I have a few more jquery / html blocks, exactly the same as above for password, email, name, etc.

onsubmit, : , , # ffc9c9.

- , # ffc9c9. , , :

 $("#*input_field_id*").css("background-color", "#ffc9c9").css("border-color", "red");

, .

, :

$("input[id='username']").css("background-color", "#ffc9c9").css("border-color", "red");

. , , . , firebug , :

$("#username").attr("name"); // = username, as expected

: $("input[id='username']") , css, $("#username") ?

+4
3

, , , . , .getElementById() document, . -.

+3

:

$("#username").css({'background-color': "#ffc9c9",'border-color': "red"});   
0

jsfiddle , #username . , , , , .

:

 if (username.length < 5 || username.length > 15 || !username_regex.test(username)) {
     $(this).find("label[for='username']").css("color", "red");
     $("#username").css("background-color", "#ffc9c9").css("border-color", "red");
 }

:

if, :

 username = 'aaa';
 error = '';
 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");
 }
0

All Articles