Nasir
Nasir

Reputation: 4865

How do I test for a empty string/null, using JavaScript?

How do I test for a input[text] field that has nothing in?

This is what I have so far:

    if ($('#StartingPrice').length == ""){
        alert("ERROR!");
    }

Any help would be greatly appreciated, Thanks

Upvotes: 3

Views: 34669

Answers (7)

Brandon McKinney
Brandon McKinney

Reputation: 1412

Just as an alternative to the already provided solutions... you could also use a Regex to test that it actually contains something other than whitespace.

!!$('#StartingPrice').val().match(/\S/)

This will test for the existing of a non-whitespace character and using the Not-Not will convert it to a Boolean value for you. True if it contains non-whitespace. False if blank or only whitespace.

Upvotes: 3

hunter
hunter

Reputation: 63502

$('#StartingPrice').length returns an integer so it will never equal "".

Try using the val() method:

if($('#StartingPrice').val() == "")
{
    alert("ERROR!");
}

.length

The number of elements in the jQuery object.

.val()

Get the current value of the first element in the set of matched elements.

.value

No Such jQuery Method Exists

Upvotes: 8

d4nt
d4nt

Reputation: 15769

I think you want this:

if ($('#StartingPrice').val() == false) {
    alert("Error!");
}

Use the .val() method to get the value and then pass that into the if. If the string is empty or white space it will evaluate to false.

Upvotes: 1

alexl
alexl

Reputation: 6851

if ($('#StartingPrice').val() === ""){
    alert("ERROR!");
}

Upvotes: 2

LooPer
LooPer

Reputation: 1479

Try:

if(myStr){
   // Your code here
}

Upvotes: -3

Naftali
Naftali

Reputation: 146302

try this:

if ($('#StartingPrice')[0].value.length == 0){
    alert("ERROR!");
}

Upvotes: 8

Raynos
Raynos

Reputation: 169363

if ($('#StartingPrice').val() == ""){
    alert("ERROR!");
}

If the value of your text input is any empty string then it's empty.

Upvotes: 1

Related Questions