92

I have the following example:

<input type="text" class="input1" value="bla"/>

Is there a way to check if this element exists and has a value in one statement? Or, at least, anything shorter then

if($('.input1').length > 0 && $('input1').val() != '')

Just getting frustrated here with mile-long conditions.

6
  • Maybe make a helper function if you use the same kind of condition many times. Commented Mar 18, 2013 at 16:14
  • 1
    if($(selector).val()) should work. If the element doesn't exist it will return 'undefined' and if it does but has no length it will return "" (which evaluates as a false). Commented Mar 18, 2013 at 16:15
  • @Benmj would 'undefined' evaluate to false as well? I thought it wouldn't. Commented Mar 18, 2013 at 16:17
  • @isherwood This is not a duplicate. I want to know if the element exists AND has a value at the same time. Commented Mar 18, 2013 at 16:18
  • 1
    @Dimskiy : it shouldn't if ($('#foobar').val()) { console.log('You will not see this') } Commented Mar 18, 2013 at 16:20

7 Answers 7

170

The input won't have a value if it doesn't exist. Try this...

if($('.input1').val())
Sign up to request clarification or add additional context in comments.

5 Comments

I ended up writing a few small functions, but this example was used, too.
@Christian: input1 is not a html tag in the above answer but is a class.
I dont complete agree to trust on the value attribute of the input element. It can at times be empty (no value inside it), yet still be present in the scope. So the best is to rely on $('.input1').length > 0 and then do whatever processing.
Empty string evaluates as false. Try it in console if("") { true } else { false } So this is the correct answer.
null value is false.
38

You could do:

if($('.input1').length && $('.input1').val().length)

length evaluates to false in a condition, when the value is 0.

3 Comments

@MarkWalters: There's no downvote here, but it's not much of an improvement over the original.
I'll upvote you Curt. The addition of .length is my preference here.
@thesystem this answer is a big improvement compared to the original. The original trusts on val(), which will evaluate to false on empty strings whereas this doesn't. That aside, upon trying the accepted answer, it failed for me, but Curt his answer did it.
13

You can do something like this:

jQuery.fn.existsWithValue = function() { 
    return this.length && this.val().length; 
}

if ($(selector).existsWithValue()) {
        // Do something
}

Comments

10

Just for the heck of it, I tracked this down in the jQuery code. The .val() function currently starts at line 165 of attributes.js. Here's the relevant section, with my annotations:

val: function( value ) {
    var hooks, ret, isFunction,
        elem = this[0];

        /// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
    if ( !arguments.length ) {

        /// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
        if ( elem ) {
            hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

            if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                return ret;
            }

            ret = elem.value;

            /// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
            return typeof ret === "string" ?
                // handle most common string cases
                ret.replace(rreturn, "") :
                // handle cases where value is null/undef or number
                ret == null ? "" : ret;
        }

        return;
    }

So, you'll either get undefined or "" or null -- all of which evaluate as false in if statements.

Comments

4

You can create your own custom selector :hasValue and then use that to find, filter, or test any other jQuery elements.

jQuery.expr[':'].hasValue = function(el,index,match) {
  return el.value != "";
};

Then you can find elements like this:

var data = $("form input:hasValue").serialize();

Or test the current element with .is()

var elHasValue = $("#name").is(":hasValue");

jQuery.expr[':'].hasValue = function(el) {
  return el.value != "";
};


var data = $("form input:hasValue").serialize();
console.log(data)


var elHasValue = $("[name='LastName']").is(":hasValue");
console.log(elHasValue)
label { display: block; margin-top:10px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <label>
    First Name:
    <input type="text" name="FirstName" value="Frida" />
  </label>

  <label>
    Last Name:
    <input type="text" name="LastName" />
  </label>
</form>

Further Reading:

Comments

0
if($('#user_inp').length > 0 && $('#user_inp').val() != '')
{

    $('#user_inp').css({"font-size":"18px"});
    $('#user_line').css({"background-color":"#4cae4c","transition":"0.5s","height":"2px"});
    $('#username').css({"color":"#4cae4c","transition":"0.5s","font-size":"18px"});

}

Comments

-1

I would do something like this: $('input[value]').something . This finds all inputs that have value and operates something onto them.

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.