简体   繁体   中英

Checking the input field is empty or not

I have this field where already a value is retrieved in PHP from mysql.. Now when I press backspace and delete the value and check whether the field is empty or not, it's still showing the field is not empty. What is the way to solve it?

$('#button').click(function(){

var name = $('#namefield').val();

if(empty(name)){
alert("The field is empty"); 

// This alert is not happening even I empty the field, maybe because of the dynamic thing
}

});



<input type="text" value="<?php echo $name;  ?>" id="namefield" />
<input type="button" id="button" value="Click" />

Just in case when I delete the value . the inspect element does not change. It still contains the value.

Unless you've defined empty as a function - it's not native. Check for blank text:

if (name.trim() == "") { alert("Empty") }
if(name.length){
 // not empty
}

And to cater for cases where the string is composed for only whitespaces you can do

if(name.trim().length)
{
  // not empty
}

Javascript doesnt have empty() like in your code. Thats most probably copied from your PHP code :)

You may not use empty() such a way in jQuery. You can try this codes. $.trim() is used to remove leading & trialing space.

$('#button').click(function(){
    var name = $('#namefield').val();
    if(!$.trim(name)){
        alert("The field is empty");
    }
});

Another jQuery-ish way to handle this - check whether the field is empty:

var name = $('#namefield');

if (name.is(':empty')) {
  alert("The field is empty"); 
}

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