stop loading image on form submit if required field - javascript

On https://bm-translations.de/#kontakt I've got a form with a submit button, that is replaced with a loading gif, when clicked.
The problem is: if one of the required fields isnt set, the form does not submit but the loading gif appears and doesnt disappear. How to say only appear if all required fields are set?
This is the HTML:
<div id="formsubmitbutton">
<input type="submit" name="submitter" value="Submit Button" onclick="ButtonClicked()">
</div>
<div id="buttonreplacement" style="margin-left:30px; display:none;">
<img src="./bilder/preload.gif" alt="loading...">
</div>
This is the JS:
function ButtonClicked()
{
document.getElementById("formsubmitbutton").style.display = "none"; // to undisplay
document.getElementById("buttonreplacement").style.display = ""; // to display
return true;
}
var FirstLoading = true;
function RestoreSubmitButton()
{
if( FirstLoading )
{
FirstLoading = false;
return;
}
document.getElementById("formsubmitbutton").style.display = ""; // to display
document.getElementById("buttonreplacement").style.display = "none"; // to undisplay
}
// To disable restoring submit button, disable or delete next line.
document.onfocus = RestoreSubmitButton;

Here you go with a solution https://jsfiddle.net/z7wfj880/2/
ButtonClicked = function(){
var validate = true;
$('input:required').each(function(){
if($(this).val().trim() === ''){
validate = false;
}
});
if(validate) {
document.getElementById("formsubmitbutton").style.display = "none"; // to undisplay
document.getElementById("buttonreplacement").style.display = ""; // to display
return true;
}
}
var FirstLoading = true;
function RestoreSubmitButton()
{
if( FirstLoading )
{
FirstLoading = false;
return;
}
document.getElementById("formsubmitbutton").style.display = ""; // to display
document.getElementById("buttonreplacement").style.display = "none"; // to undisplay
}
// To disable restoring submit button, disable or delete next line.
document.onfocus = RestoreSubmitButton;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="First Name" required/>
<input type="text" placeholder="Middle Name"/>
<input type="text" placeholder="Last Name" required/>
<div id="formsubmitbutton">
<input type="submit" name="submitter" value="Submit Button" onclick="ButtonClicked()">
</div>
<div id="buttonreplacement" style="margin-left:30px; display:none;">
<img src="./bilder/preload.gif" alt="loading...">
</div>
First of all do a trim of required input field, so that if any user provide spaces it will remove the extra spaces in front & end.
Loop through all the required input & check for empty input.

You can create a modular function to display and hide the loader.
Now when you click the submit button, you can check for your form validation and toggle the loader easily. I have hardcoded the false, but you can check for the appropriate validation.
function displayLoading(form, loader) {
document.getElementById("formsubmitbutton").style.display = form; // to undisplay
document.getElementById("buttonreplacement").style.display = loader; // to display
}
function ButtonClicked()
{
if(false) { // form in valid
displayLoading('none', '');
} else {
displayLoading('', 'none');
}
}
var FirstLoading = true;
function RestoreSubmitButton()
{
if( FirstLoading )
{
FirstLoading = false;
return;
}
document.getElementById("formsubmitbutton").style.display = ""; // to display
document.getElementById("buttonreplacement").style.display = "none"; // to undisplay
}
// To disable restoring submit button, disable or delete next line.
document.onfocus = RestoreSubmitButton;
<div id="formsubmitbutton">
<input type="submit" name="submitter" value="Submit Button" onclick="ButtonClicked()">
</div>
<div id="buttonreplacement" style="margin-left:30px; display:none;">
<img src="http://gph.is/1cYmtb9" alt="loading...">
</div>

Check for validation of required fields.
If all fields are set then only call buttonreplacement.
For Eg: If you have fields field1 and field2.
f1 = document.getElementById("id_field1").value;
f2 = document.getElementById("id_field2").value;
if (f1!=null || f1!=undefined || f1!="" || f2!=null || f2!=undefined || f2!=""){
document.getElementById("buttonreplacement").style.display = "none";
}
else{
document.getElementById("buttonreplacement").style.display = "block";
}
You can always improve your code using Jquery.

Related

Check if checkbox is checked before submit

I have form with steps. On last step I have to send form to another page. On my script, I have checked inputs and select. But how can I add a check if checkbox is checked, and if not checked restrict sending?
I am trying this:
<form id="regForm" method="POST" action="my action">
<div class="tab">FIRST Tab</div>
<div class="tab">END TAB BEFORE SUBMIT
<input placeholder="Name" oninput="this.className = ''" name="first_name" value="">
<input placeholder="Last Name" oninput="this.className = ''" name="first_name" value="">
<label id="chkbx"><font color="red">Yes</font>, OK TEST
<input type="checkbox" oninput="this.className = ''"></label>
</div>
BUTTONS NEXT AND PREVIUS ON LAST PAGE CHANGE NEXT BUTTON TO SUBMIT
<button type="button" class="button-base button-blue wow animated" data-wow-duration="2s" data-wow-delay="0s" data-wow-iteration="10" id="prevBtn" onclick="nextPrev(-1)">Назад</button>
<button type="button" class="button-base button-blue wow animated" data-wow-duration="2s" data-wow-delay="0s" data-wow-iteration="10" id="nextBtn" onclick="nextPrev(1)"><i class="fas fa-cart-plus"></i> Продължете с поръчката</button>
</form>
And my javascript used for everything like change tab, submit tab, check tab...
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form ...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
// ... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Към плащане";
} else {
document.getElementById("nextBtn").innerHTML = "<i class='fas fa-cart-plus'></i> Продължете с поръчката";
}
// ... and run a function that displays the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, b, y, n, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
n = x[currentTab].getElementsByTagName("select");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false:
valid = false;
}
}
for (i = 0; i < n.length; i++) {
// If a field is empty...
if (n[i].value == "") {
// add an "invalid" class to the field:
n[i].className += " invalid";
// and set the current valid status to false:
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class to the current step:
x[n].className += " active";
}
You can follow this code and instructions:
first, you call a function in submit
<FORM NAME="myForm" onSubmit="return yourFunction()">
Check the checkbox is checked by using jquery
function yourFunction(e) {
e.stopPropagation();
e.preventDefault();
return ($('#mycheck').is(':checked'));
}
when the checkbox is checked then approve submit otherwise not submit
2nd process is
$('#myform').on('submit', function(event) {
event.preventDefault();
event.stopPropagation();
($('#mycheck').is(':checked'))?console.log('submit allow') : console.log('Not allow submit');
return ($('#mycheck').is(':checked'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" id="myform">
<input type="text" >
<input type="checkbox" id="mycheck">
<button>submit</button>
</form>
== Thanks ==
HTML code:
<form action="./addUser.htm" onsubmit='return myfunction();' method="POST" autocomplete="off">
<input type="checkbox" id="ABC" name="ParamList" class="clonecheckbox" value="ABC"> ABC
<input type="checkbox" id="PQR" name="ParamList" class="clonecheckbox" value="PQR"> PQR
<input type="checkbox" id="XYZ" name="ParamList" class="clonecheckbox" value="XYZ"> XYZ
...
...
...
...
<input class="btn btn-outline-success" type="submit" value="Add " id="adduser" />
</form>
JS code:
For any one of them
function myfunction() {
var selectedCheckbox = $('input:checkbox:checked.clonecheckbox').map(function () {
return this.value;
}).get();
if($('.clonecheckbox:checked').length == 0) {
return false;
} else {
return true;
}
}
OR
For single ckeckBox using Jquery
if ($('#ABC').prop("checked")) {
return true;
}else{
return false;
}
// OR
if($('#ABC').prop("checked") == true){
return true;
}else{
return false;
}
<input type="checkbox" oninput="this.className = ''"></label>
Add id field in the checkbox
<input type="checkbox" id="checkBoxId" oninput="this.className = ''"></label>
You can verify check box is checked before form submit.
document.getElementById("regForm").submit();
Replace this line by the following
if(document.getElementById('checkBoxId').is(':checked')){
document.getElementById("regForm").submit();
}else{
//anything you want
}

what is the correct way to validate form with javascript

should i put "submit" instead "form_name" in the last block of code? what is the correct way?
thanks!
function check() {
var title = document.getElementById("title");
var content = document.getElementById("content");
if (title == "") {
alert("title is required");
return false;
}
if (content == "") {
alert("content is required");
return false;
}
var submit = document.getElementById("form_name");
submit.submit();
}
this is my form
<form action="#" method="post" id="form_name" name="form_name">
<input type="text" name="title" id="title" />
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit" value="Submit" id="submit" name="submit" onclick="return check();"/>
</form>
First you are selecting an element and acting like it is the value
var title = document.getElementById("title"); <-- DOM element
if (title == "") { <-- checking the DOM against a string.
You should be using .value to get what was entered.
Next you are submitting the form.... but you clicked on a submit button inside of the form so that will submit the form. So that is not needed.
function check() {
var title = document.getElementById("title").value;
var content = document.getElementById("content").value;
if (!title.trim().length) {
alert("title is required");
return false;
else if (!content.trim().length) {
alert("content is required");
return false;
}
return true
}
And never name anything submit, it just leads to problems.
In most recent browsers you have more power to use
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}else{
document.getElementById("demo").innerHTML = "";
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
Reference:
https://www.w3schools.com/js/js_validation_api.asp

Show loading gif onkeypress

So I have an input and dataList:
<div id="namearea">
<h2>City Name:</h2>
<div>
<input id="citiesinput" list="cities">
<datalist id="cities"></datalist>
<button id="search">
Search
</button>
<span class="loading" id="loadingnames">
<img src="/gif" alt="icon" />
Loading...
</span>
</div>
</div>
I have already used JS to fill the dataList with options.
What I want to do is display the loading gif from when i start typing in the input until I have chosen an option or pressed the search button
current JS:
var cityArray;
window.onload = function() {
processCities();
document.getElementById("search").onclick = findWeather;
document.getElementById("citiesinput").addEventListener("onkeypress", showLoad);
};
function showLoad () {
var input = document.getElementById("citiesinput").value;
if(input !== "" || cityArray.indexOf(input) == -1) {
document.getElementById("loadingnames").style.display = "block";
}
}
I have put a fiddle together for you here. I use the keyup event because the keypress event is called before the first key is registered in the input value.
input.addEventListener('keyup', function(){
loading.style.display = input.value.length ? 'block' : 'none';
});
You must also remember to remove the loader if the condition is not met.
Use opacity instead of display. Reason being when you set the display to inline-block, you will find your parent div "glitching" its height to adjust its content to the image div
Use keyup event after you press a key, it will trigger the function
var cityArray;
cityArray = ["city1", "city2"]
function findWeather() {
}
window.onload = function() {
//processCities();
//document.getElementById("search").onclick = findWeather;
document.getElementById("citiesinput").addEventListener("keyup", showLoad);
document.getElementById("search").addEventListener("click", showLoad);
};
function showLoad() {
var input = document.getElementById("citiesinput").value.trim();
if (input == "") {
document.getElementById("loadingnames").style.opacity = "0";
return
}
if (cityArray.indexOf(input) == -1) {
document.getElementById("loadingnames").style.opacity = "1";
} else {
document.getElementById("loadingnames").style.opacity = "0";
}
}
<div id="namearea">
<h2>City Name:</h2>
<div>
<input id="citiesinput" list="cities">
<datalist id="cities"></datalist>
<button id="search">
Search
</button>
<span class="loading" id="loadingnames" style="opacity:0;">
<img src="http://bestwallpaperhd.com/wp-content/uploads/2012/12/animated-wallpaper-gif.gif" alt="icon " id="city_img " style="width:50px;height:50px;"/>Loading...
</span>
</div>
</div>

Javascript/jQuery form validation

I got most of this form validation to work properly but the only issue is that when the form detects an error on submit and the user corrects the mistake, the error text won't go away. This can be confusing for the user but I can't seem to figure out a way to make the error text disappear with the way that I am doing this. Also I know I have the option of PHP validation but there is a few reasons why I want to use this front end validation. Here is the whole validation script for the form. The submit portion is at the bottom:
JavaScript/jQuery
var valid = 0;
function checkName(elem) {
//gather the calling elements value
var val = document.getElementById(elem.id).value;
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span>Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
valid++;
}
}
function checkEmail(elem) {
var val = document.getElementById(elem.id).value;
//Check email format validity
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
valid++;
}
}
function checkMessage(elem) {
var val = document.getElementById(elem.id).value;
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
valid++;
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
function checkSubmit() {
if (valid == 3) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
//If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if (valid < 3) {
document.getElementById("errorSubmit").innerHTML = "<span>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
HTML Form
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="cform" id="contact-form">
<form id="form13" name="form13" role="form" class="contactForm" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate
action="https://Some3rdPartyPOSTService">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" name="Field1" class="form-control" id="name" placeholder="Tony Stark" onblur="checkName(this)"/>
<span id="errorName" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" class="form-control" name="Field4" id="email" placeholder="" data-rule="email" data-msg="Please enter a valid email" onblur="checkEmail(this)"/>
<span id="errorEmail" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="Field3" id="message" rows="5" data-rule="required" data-msg="Please write something here" onblur="checkMessage(this)"></textarea>
<span id="errorMessage" style="margin-left:10px;"></span>
</div>
<span id="errorSubmit" style="margin-left:10px;"></span>
<button type="submit" class="btn btn-theme pull-left">SEND MESSAGE</button>
</form>
</div>
</div>
<!-- ./span12 -->
</div>
</div>
</section>
Simply put your check on onChange event callback, if:
var x = getElementById("formid"); // then add a listener
x.addEventListener('change', function () {
callback with your code that examines the form
});
Or listen for a specific text box change event, that would be the simplest way, and look for a way to disable submit if the conditions aren't met.
Add an onchange event to your text inputs that will remove the error message.
Rather than making a count of valid fields, I would also check for the existence of error messages. This will make it easier to add more fields to your form.
function checkName(e) {
//gather the calling elements value
var val = $(e.target).val();
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span class="errmsg">Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span class='errmsg'>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
}
}
function checkEmail(e) {
var val = $(e.target).val();
//Check email format validity
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span class='errmsg'>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
}
}
function checkMessage(e) {
var val = $(e.target).val();
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
$('#name').change(checkName);
$('#email').change(checkEmail);
$('#message').change(checkMessage);
function checkSubmit() {
if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
}
/If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
Since you were already using jQuery, I modified the code to use more of the jQuery functionality to make things easier. Now when a form field is modified and the element loses focus, the validation will occur immediately. We also no longer need to know how many error messages could potentially appear (though you never had a decrement operation for corrected values so the valid could become greater than 3). Instead we just make sure that there isn't more than 0 of them.
I've removed your onblur html attributes and replaced them by JavaScript keyup events. This will allow your script to check everything as soon as the user type something :
document.getElementById("message").addEventListener('keyup', function () {
checkMessage(this);
});
document.getElementById("email").addEventListener('keyup', function () {
checkEmail(this);
});
document.getElementById("name").addEventListener('keyup', function () {
checkName(this);
});
JSFIDDLE

Textbox value compare before submitting

I want to let my two textboxes be checked before those get submitted.
like
if textbox1 >= textbox2 submit
else show errorlabel and dont submit.
How can i do this?
Provide your onclick handler's implementation to extract the value of the two text boxes, then parse them as an int.
function submitForm() {
var first = parseInt(document.getElementById("first"), 0);
var second = parseInt(document.getElementById("second"), 0);
if(first >= second) {
// ...
return true;
} else {
var hiddenTextBox = document.getElementById("error");
hiddenTextBox.style.visibility = "visible";
return false;
}
}
This assumes you have two elements with id="first" and id="second" respectively, and a hidden element with id="error"
Try it like,
$('#submitId').on('click',function(){
if $('#textbox1').val() < $('#textbox2').val()){
$('#erroLabel').show(); // showing error label
return false; // to prevent submitting form
}
});
You can make function in javascript,
<script type="text/javascript">
function checkValues()
{
var searchtext1 = document.getElementById("textbox1").value;
if(searchtext1=='')
{
alert('Enter any character');
return false;
}
var searchtext2 = document.getElementById("textbox2").value;
if(searchtext2=='')
{
alert('Enter any character');
return false;
}
}
</script>
and then in html form
<form method='GET' onSubmit="return checkValues();">
<input type="text" id= "textbox1" name="textbox1" class='textbox' >
<input type="text" id= "textbox2" name="textbox2" class='textbox' >
<input type="submit" id='submit' value="Search" class ='button' >
</form>

Categories

Resources