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.
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.
You can select all the inputs
type text
and filter them checking for the value being present:
$(function () {
$("#Check").on("click", function () {
// Will return the inputs containing value.
var anyValue = $("input[type=text]").filter(function () {
return $(this).val().trim() !== "";
});
// If there's at least one containing any value.
console.log(anyValue.length !== 0);
});
});
I considered the markup below:
<input name="Name" id="Name" type="text" placeholder="Name" />
<input name="City" id="City" type="text" placeholder="City" />
<input name="State" id="State" type="text" placeholder="State" />
<input name="Zip" id="Zip" type="text" placeholder="Zip" />
<button id="Check">Check</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.