88

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.

william.eyidi
  • 2,315
  • 4
  • 27
  • 39
Dimskiy
  • 5,233
  • 13
  • 47
  • 66
  • Maybe make a helper function if you use the same kind of condition many times. – mirrormx Mar 18 '13 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). – Ben Jacobs Mar 18 '13 at 16:15
  • @Benmj would 'undefined' evaluate to false as well? I thought it wouldn't. – Dimskiy Mar 18 '13 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. – Dimskiy Mar 18 '13 at 16:18
  • 1
    @Dimskiy : it shouldn't `if ($('#foobar').val()) { console.log('You will not see this') }` – Ben Jacobs Mar 18 '13 at 16:20
  • @Dimskiy Both questions have been asked countless times. It's fairly trivial to combine them. – isherwood Mar 18 '13 at 16:23

7 Answers7

166

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

if($('.input1').val())
Brian
  • 37,399
  • 24
  • 94
  • 109
38

You could do:

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

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

Curtis
  • 101,612
  • 66
  • 270
  • 352
  • @MarkWalters: There's no downvote here, but it's not much of an improvement over the original. – the system Mar 18 '13 at 16:17
  • I'll upvote you Curt. The addition of .length is my preference here. – Robert Waddell Sep 14 '13 at 19:48
  • @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. – I try so hard but I cry harder Dec 12 '20 at 23:07
13

You can do something like this:

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

if ($(selector).existsWithValue()) {
        // Do something
}
97ldave
  • 5,249
  • 4
  • 25
  • 39
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.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Ben Jacobs
  • 2,526
  • 4
  • 24
  • 34
3

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:

KyleMit
  • 30,350
  • 66
  • 462
  • 664
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"});

}
zmag
  • 7,825
  • 12
  • 32
  • 42
-1

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

BWP
  • 1