Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if ($('#selector').length == 0) doesn't work in IE7 and IE8

Here is my jquery code:

$(document).ready(function() {

    if ($('#login').length == 0) {
        $('#login').css('background', "url('/css/login-bg.gif') 2px center no-repeat");
    }
    if ($('#password').length == 0) {
        $('#password').css('background', "url('/css/password-bg.gif') 2px center no-repeat");
    }

    $('#login').focus(function() {
        $(this).css('background', 'transparent'); 
    });

    $('#password').focus(function() {
        $(this).css('background', 'transparent'); 
    });

});

It works in Firefox but not in IE7 or IE8. Why?

The purpose of this code: It is supposed to display a user friendly text inside sign in form so users know what to fill in username and password input fields. This is important because input fields don't have labels (I know... but client just does not want labels there).

The if ($('#selector').length == 0) condition is there because if user saves his/her username and password in the browser, the browser will fill in the saved values automatically, so it makes sure the background image doesn't overlap them.

like image 389
Richard Knop Avatar asked Feb 28 '23 12:02

Richard Knop


1 Answers

You should be using:

if($('#selector').val() == '')

instead of

if ($('#selector').length == 0)

$('#selector').length will only tell you how many elements were matched, not the length of the value of the selected elements. See here: http://api.jquery.com/length/

like image 66
Mike Sherov Avatar answered Mar 12 '23 18:03

Mike Sherov