Show error message box only if all input fields are empty - javascript

I have 4 textboxes, and I need to make sure that before submitting I have at least one of the textboxes filled.
HTML:
<form name="parentForm">
<input name="pf1" id="pf1" type="text">
<input name="pf2" id="pf2" type="text">
<input name="pf3" id="pf3" type="text">
<button type="button" onClick="submit()">Submit</button>
</form>
Javascript:
function submit()
{
if ($.trim($("#pf1").val()) === "" || $.trim($("#pf2").val()) === "" || $.trim($("#pf3").val()) === "")
{
alert ('Fields are empty.');
return false;
}
...
}
the problem is that it only submit if all fields are filled, in my case what iI want is that if only 1 textbox has data, I can submit the form.

Instead of || operator use && operator to check for all inputs.
Instead you can compare the count of empty inputs with the total inputs using filter. If they are equal, it mean all input fields are empty.
function submit() {
const emptyInputs = $('input').filter(function() {
return $(this).val().trim() == "";
});
if (emptyInputs.length === $('input').length) {
alert('Fields are empty.');
return;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="pf1" id="pf1" type="text">
<input name="pf2" id="pf2" type="text">
<input name="pf3" id="pf3" type="text">
<button type="button" onClick="submit()">Submit</button>

if only one field must be filled with a value change your or to and
function submit()
{
if ($.trim($("#pf1").val()) === "" && $.trim($("#pf2").val()) === "" && $.trim($("#pf3").val()) === "")
{
alert ('Fields are empty.');
return false;
}
...
}

Make a loop on all inputs and if at least one is different than empty submit:
$("input").each(function(){
if($(this).val() != ""){
// submit
}
})

Related

How to get the search to work when the user presses enter

This is the button Iv`e created and search bar that has a function to go to a page when a user clicks search tab but I need it to work when the user presses enter as well.
This is the search bar and button
<input type="text" method="get" class="form-control" id="search" placeholder="Search" value="">
<button type="button" id="go" class="btn btn-default" onclick="sendToPage();">Search</button>
This is the function
function sendToPage(){
var input = document.getElementById("search").value;
//Check to see if the user has entered apple/iphone;
if (input === "apple"){
//location.href="apple.html";
location.replace("apple.html");
return false;
}
else if (input === "iphone"){
location.replace("apple.html");
return false;
}
}
Putting a form around the input should give you the result you're looking for. Then just add an "onsubmit" to the form that calls your sendToPage(); function.
You can add a keyup and check its event.keyCode. If the key code is 13, it means the user clicked enter while on the input text.
Something like this:
document.getElementById("search")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode == 13) {
if (input === "apple")
location.replace("apple.html");
else if (input === "iphone")
location.replace("apple.html");
}
return false;
});
Or using your function sendToPage():
document.getElementById("search")
.addEventListener("keyup", function(event) {
event.preventDefault();
sendToPage();
return false;
});
It seems the id of your input field is 'search' so you can try this:
note that the keycode of enter is 13. so we can compare the input codes with 13. if its true then do the search.
$('#search').keydown(function(event) {
if (event.keyCode == 13) {
var input = $(this).val();
if (input === "apple"){
//location.href="apple.html";
location.replace("apple.html");
return false;
}
else if (input === "iphone"){
location.replace("apple.html");
return false;
}
return false;
}
});
});
This is the button
<!-This is the button -->
<div id="search-bar">
<div class="form-group">
<input type="text" method="get" class="form-control" id="search" placeholder="Search" value="">
<button type="button" id="go" class="btn btn-default" onclick="sendToPage();" onChange="aliasonclick">Search</button>
</div>
</div>

Form Validation not working on all fields but only the first

When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.

jQuery/JS Input verification

This is my simple form. I want to validate both inputs if it has some value inserted and that value is not a spaces. How can I achieve such functionality before request gets submitted to server side? Thanks a lot!
<form:form method="post" action ="${addQueryOverride}">
<label>Enter query string and product list ID: </label>
<input maxlength="30" class="text span-1" name="queryOverride" id="queryOverrideId"/>
<input onkeypress="return isNumberKey(event)" maxlength="30" class="text span-1" name="productList" id="productListId"/>
<input type="submit" value="Add">
</form:form>
$(function() { // when page load
$("form").on("submit",function(e) {
if ($.trim($("#queryOverrideId").val()) == "") {
alert("Please enter query");
$("#queryOverrideId").focus();
return false;
}
var id = $("#productListId").val();
if ($.trim(id) == "" || isNaN(id)) {
alert("Please enter product list");
$("#productListId").focus();
return false;
}
});
});
On submit, iterate over each of the fields and run a check:
$("form input:text").each(function() {
var isValid = this.value.length > 0 && this.value.indexOf(" ") == -1;
return isValid; //if true, go to next element, if false, break each loop
});

How to validate 3 fields in javascript

I want to validate 3 fileds
First name text box
Last name text box
Middle name text box
here is my code:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["lname"].value;
var z=document.forms["myForm"]["mname"].value;
if(((x!='') && (y=='' && z==''))
|| ((y!='') && (x=='' && z==''))
|| ((z!='') && (x=='' && y=='')))
{
alert("First name must be filled out");
return false;
}
alert("fill input filed");
return false;
}
</script>
My code is executing like this: if i wont enter anything in any field - alerting, this part is fine. Then when i enter one of the field its alerting me the if part same way if i will enter two text box my if part should be executed, but its not happening.
Can you change that condition please so that if I will fill 2 fields it should alert me at least one field can be filled?
Make it simple, your first name is mandatory, so make it first priority
if(x==''){
alert("First name must be filled out");return false;
if(y=='' && z==''){
//alert();// other condtions
}
}else{
alert("fill input filed");return false;
}
I think this is what you are looking for...
Javascript Code
<script type="text/javascript">
function validateForm()
{
var x=document.getElementById("fname").value;
var y=document.getElementById("mname").value;
var z=document.getElementById("lname").value;
if((x==''))
{
alert("First name must be filled out");
return false;
}
else if((y==''))
{
alert("Middle name is empty");
return false;
}
else if((z==''))
{
alert("Last name is empty");
return false;
}
return true;
}
</script>
HTML Code
<form action="#">
<input type ="text" id ="fname"></input>
<input type ="text" id ="mname"></input>
<input type ="text" id ="lname"></input>
<input type="submit" onclick="return validateForm();">
</form>

How to check if the user has not entered the data to a form (befor sending)?

I have some input form on names: owner, number, city
<input id="id_owner" type="text" name="owner" maxlength="250" />
<input id="id_number" type="text" name="number" maxlength="250" />
<input id="id_city" type="text" name="city" maxlength="250" />
How to check if the user has not entered the data to a form (befor sending) that does not show this dialog from this code:
<a type="submit" name"save-continue-to-review" data-toggle="modal" data-target="#dialog" href=""
class="btn primary btn-primary" title="Order">Order
</a>
and it will show another
Here is full code: http://wklej.org/id/927806/
Eventually you'll be able to use HTML5 form validation. But until then, use some jQuery code like this. (only because you tagged the question with jQuery. You could potentially do it with vanilla JS.)
(un-tested code, but should work)
var fields = $('input')
$('form').submit(function(e){
e.preventDefault()
valid = true
fields.each(function(){
if ($(this).val() == null) {
valid = false
}
});
if (valid == true) {
$('form').submit()
} else {
alert("At least one field was not valid!")
}
});
1) Add this on your form
onsubmit="return validateForm(this);"
2)The validate function (checks if fields are empty)
function validateform(formObj)
{
inputs = formObj.GetElementsByTagName('input');
for(i=0; i < inputs.length; i++)
{
if($.trim(inputs[i].value) == '')
{
alert('Field: ' + inputs[i].name + ' is empty!');
return false;
}
}
return true;
}
if ( !$(this).val() ) {
valid = false
}
maybe this post is useful for you

Categories