简体   繁体   中英

Detect if user didn't input anything/deleted input jQuery

I have an input field where users can input text, when they type something in, and it's valid, an image will appear. Same goes for inputting the wrong text.

I would like to change/remove the image when there is nothing in the input field.

Here's my code, but it doesn't seem to be working:

$('#input_link').on('mouseout', function(){
    if($.trim($('#input_link').val().length = 0)){
        $('#status_image').attr('src', 'images/link_related/stand_by.png');
    }
    });

Try:

   $('#input_link').on('mouseout', function(){
     if(!$.trim(this.value).length){
         $('#status_image').attr('src', 'images/link_related/stand_by.png');
     }
   });

Your bracket for trim was out of place and you were using assignment operator instead of comparison. I think mouseout might not be a good event to do what you are doing. Use keyup or change event based on when exactly you want to show the image.

Probably this is what you are trying to achieve.

$('#input_link').on('input keyup paste', function () {
    var hasValue = $.trim(this.value).length;
    $('#status_image').attr('src', function () {
        return hasValue ? 'http://placehold.it/20/00ff00' : 'http://placehold.it/20/ff0000';
    });
});

Demo

use == or === to compare things,

if($.trim($('#input_link').val().length == 0)){'

Try this,

$('#input_link').on('mouseout', function(){
    if($.trim($('#input_link').val()).length == 0){
        $('#status_image').attr('src', 'images/link_related/stand_by.png');
    }
    });

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