Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check if <input> exists and has a value

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.

like image 497
Dimskiy Avatar asked Mar 18 '13 16:03

Dimskiy


People also ask

How can check input value or not in jQuery?

Answer: Use the jQuery val() Method You can use the val() method to test or check if inputs are empty in jQuery. The following example will add a red outline around the inputs if it is focused but not filled out.

How do you check if a field has a value in Javascript?

var el = document. getElementById("customx"); if (el !== null && el. value === "") { //The element was found and the value is empty. }


5 Answers

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

if($('.input1').val())
like image 191
Brian Avatar answered Oct 04 '22 14:10

Brian


You could do:

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

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

like image 34
Curtis Avatar answered Oct 04 '22 13:10

Curtis


You can do something like this:

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

if ($(selector).existsWithValue()) {
        // Do something
}
like image 26
97ldave Avatar answered Oct 04 '22 14:10

97ldave


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.

like image 38
Ben Jacobs Avatar answered Oct 04 '22 13:10

Ben Jacobs


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:

  • Make jQuery :contains Case-Insensitive
  • Make Your Own Custom jQuery Selector
  • Exploring jQuery Selectors, Part 3
like image 45
KyleMit Avatar answered Oct 04 '22 13:10

KyleMit