user2574220
user2574220

Reputation:

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.

Upvotes: 0

Views: 4343

Answers (4)

Hanky Panky
Hanky Panky

Reputation: 46900

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 :)

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36458

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"); 
}

Upvotes: 0

MH2K9
MH2K9

Reputation: 12039

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");
    }
});

Upvotes: 0

tymeJV
tymeJV

Reputation: 104795

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

if (name.trim() == "") { alert("Empty") }

Upvotes: 1

Related Questions