Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery if text input does *not* equal blank

Tags:

jquery

I am trying to work out how to do something if a certain text box is not empty (i.e. contain something, could be anything)

This is my code (that doesnt seem to work)

if ( !($('#edit-sPostalCode').attr('val','')) ) {
    stuff here
}

What have I missed?

like image 998
Adi Avatar asked Nov 11 '11 15:11

Adi


2 Answers

if ( $('#edit-sPostalCode').val() != '' ) {
    stuff here
}

$('#edit-sPostalCode').attr('val','') will actually create an attribute of the input box with a value of '' and will then return a jQuery object.

Saying !($('#edit-sPostalCode').attr('val','')) will then negate that jQuery object. As an instance of an object is truthy in JS the result of this expression will always be false.

like image 178
El Ronnoco Avatar answered Sep 22 '22 10:09

El Ronnoco


Are you aware of the .val method?

if ( $('#edit-sPostalCode').val() !== '' ) {

Although you ought to $.trim the value if you consider whitespace as being equivalent to nothing at all:

if ( $.trim( $('#edit-sPostalCode').val() ) !== '' ) {
like image 40
Blazemonger Avatar answered Sep 19 '22 10:09

Blazemonger