jQuery check if <input> exists and has a value

JavascriptJquery

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

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

Solution 2 - Javascript

You could do:

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

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

Solution 3 - Javascript

You can do something like this:

jQuery.fn.existsWithValue = function() { 
    return this.length && this.val().length; 
}
    
if ($(selector).existsWithValue()) {
        // Do something
}

Solution 4 - Javascript

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.

Solution 5 - Javascript

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:

Solution 6 - Javascript

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"});

}

Solution 7 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDimskiyView Question on Stackoverflow
Solution 1 - JavascriptBrianView Answer on Stackoverflow
Solution 2 - JavascriptCurtisView Answer on Stackoverflow
Solution 3 - Javascript97ldaveView Answer on Stackoverflow
Solution 4 - JavascriptBen JacobsView Answer on Stackoverflow
Solution 5 - JavascriptKyleMitView Answer on Stackoverflow
Solution 6 - JavascriptMirza Arsal ChaudhryView Answer on Stackoverflow
Solution 7 - JavascriptBWPView Answer on Stackoverflow