简体   繁体   中英

Focus on input and remove focus using Jquery

I'm tying to check if the input has focus to add color to the back ground However when I remove the mouse and focus on another input it doesn't remove the focus anymore it actually stays with the focus! how can I remove the backgound from the first one!

Fullname: <input type="text" name="name"><br>
Email: <input type="text" name="email">

How can I check that the class test exists

I'm tying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
});

I would approcialte it if you can test this for me or let me know what's going wrong on the above code!?

You can use the .blur

$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
    $("input").blur(function(){
        $(this).css("background-color", "#ffffff");
    });
});

Or you can add class to each part of the html code:

Name: <input class="name" type="text" name="fullname"><br>
Email: <input class="email" type="text" name="email">

And use the following JQuery code to run it.

$(document).ready(function(){
    $(".name").focus(function(){
        $(this).css("background-color", "#f4fcef");
        $(".email").css("background-color", "#ffffff");        
    });
    $(".email").focus(function(){
        $(this).css("background-color", "#f4fcef");
        $(".name").css("background-color", "#ffffff");        
    });
});

For better way you can use CSS:

input:focus {
    background-color: yellow;
}

but with using jquery:

$('input[type="text"]').focus(function() {
    $(this).css("background-color", "#cccccc");
});

$('input[type="text"]').blur(function() {
    $(this).css("background-color", "#fff");
});

you can check that if class exist on focus then do some action same on focus out.

 $(document).ready(function(){
$("input").focus(function(){
    if($(this).hasClass("yourclassName")){
     $(this).css("background-color", "#f4fcef");
    }

}).focusout(function(){
   if($(this).hasClass("yourclassName")){
     $(this).css("background-color", "#f4fcef");//some other color.
    }
});

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM