If ($ ('# selector'). Length == 0) does not 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 should display convenient text inside the login form so that users know what to fill in the username and password input fields. This is important because the input fields do not have shortcuts (I know ... but the client just doesn’t want marks there).

The value is if ($ ('# selector'). Length == 0), because if the user saves his username and password in the browser, the browser automatically fills in the saved values, so it ensures that the background image does not overlap them.

+4
source share
1 answer

You should use:

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

instead

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

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

+8
source

Source: https://habr.com/ru/post/1302308/


All Articles