user1186050 user1186050 - 6 months ago 10
jQuery Question

Check to see if at least one input field out of many has a value

I have 4 input fields and I want to check to see if at least 1 has a value. If none have values I want to return.

Here is what I have and I know if doesn't work because it doesn't enter the if statement if nothing has been entered.



if ($('#Name').val() != "" && $('#State').val() != "" && $('#City').val() != "" && $('#Zip').val() != "") {
showAlert("You need to select at least one of the following: Name, State, City, or Zip", 'error');
return;
}





if none have a value I want to show a message and return without further processing.

Answer

So instead of checking that the value is not empty you should check that they ARE empty:

if (!$('#Name').val() && !$('#State').val() && !$('#City').val() && !$('#Zip').val()) {
  return alert("You need to select at least one of the following: Name, State, City, or Zip", 'error');
}

You can also put the alert after the return to make it shorter.

Fiddle