Jquery if text input * not * equals empty

I am trying to decide how to do something if a certain text field is not empty (i.e. there is something, maybe anything)

This is my code (which doesn't seem to work)

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

What did I miss?

+6
source share
3 answers
 if ( $('#edit-sPostalCode').val() != '' ) { stuff here } 

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

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

+11
source

Do you know about the .val method?

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

Although you should have a $.trim value, if you consider space as the equivalent of nothing:

 if ( $.trim( $('#edit-sPostalCode').val() ) !== '' ) { 
+2
source
 if ( !($('#edit-sPostalCode').val() === '') ) { stuff here } 
0
source

Source: https://habr.com/ru/post/901303/


All Articles