6

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?

1
  • There is no HTML element which has a val attribute. I think you mean the jQuery method .val(). Commented Nov 11, 2011 at 15:05

3 Answers 3

11
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.

Sign up to request clarification or add additional context in comments.

1 Comment

It would not set the value, it will add a new attribute with name val. But apart from that, you are right.
2

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() ) !== '' ) {

4 Comments

is !== a javascript operator? I know === is
Just googled it there - is this the best for this comparison?
@NicholasMurray It might not matter, but it's better to be safe. For instance, in JavaScript, false=='0' is true. false=='' is also true, although ''=='0' is false.
@FelixKling - cool I've changed my answer to use === instead.
0
if ( !($('#edit-sPostalCode').val() === '') ) {
    stuff here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.