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
}
Related
i am trying to make a multi-step questionnaire where there are 3 steps. This questionnaire allows users to input their desired answers and will return company names that are in the selected category, features and integration needed. This data is stored in the MySQL database, i will attach a diagram of the schema.
Diagram
Step 1 is category, uses radio button as only one can be selected.
Step 2 is Features, uses checkbox as multiple items can be selected
Step 3 is integration, uses radio button as only one can be selected.
The way i have tried to implement this is to include the user input value into the SQL select query and then use the results as the next step values. The issue i have is, as it is multi-step the second query does not run until the full questionnaire is submitted. Also i get the feeling this not the right way to do it as questions will not load if the database does not respond quickly.
Can i implement Javascript to do the multi-step logic and then run one query at the end? i am kind of lost on how to go about this.
Any help with be greatly appreciated.
App.py
#app.route('/home', methods = ['GET', 'POST'])
def home():
firstInput = ''
myresult2 = ''
sqlFirst = 'SELECT DISTINCT * FROM categories;'
if request.method == 'POST':
firstInput = request.form.get('cat_in')
my_data = (firstInput,)
fetchFetch = 'SELECT distinct features.features, categories.categories, mytable.cat_FK_KEY, categories.categoryID, mytable.Categories FROM mytable, features, nameFeatures, categories WHERE mytable.id = `nameFeatures`.`name_FK_ID` and features.featureID = nameFeatures.feature_FK_ID and mytable.cat_FK_KEY = categories.categoryID and categories.categoryID = %s;'
cursor.execute(fetchFetch, my_data)
myresult2 = cursor.fetchall()
cursor.execute(sqlFirst)
myresult = cursor.fetchall()
return render_template('index.html', firstInput=firstInput, myresult=myresult, myresult2=myresult2)
index.html
<form id="regForm" action="" method="post">
<div class="tab">Please pick a Category:
{% for row in myresult %}
<input type="radio" id="{{row[0]}}" oninput="this.className = ''" name="cat_in" value="{{row[0]}}">
<label for="{{row[0]}}">{{row[1]}}</label><br>
{% endfor %}
</div>
<div class="tab">Select the features:
<p>{{firstInput}}</p>
{% for row in myresult2 %}
<input type="checkbox" id="{{row[0]}}" oninput="this.className = ''" name="feature_in" value="{{row[0]}}">
<label for="{{row[0]}}">{{row[0]}}</label><br>
{% endfor %}
</div>
<div class="tab">Which intergration:
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<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 = "Submit";
document.getElementById("nextBtn").submit();
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display 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);
console.log(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// 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;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
console.log(valid);
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 on the current step:
x[n].className += " active";
}
</script>
so I have made validation form with a input field called password, So the criteria of the password is that the password's length should be atleast 5 characters long. When user submit's the blank input field a error called **Password is too short. is thrown. Now what I want when users again starts writing in the password input field the error should be hidden, in my case I was able to hide error when the input is more than 5 characters ,the error message disappears only when the characters are more than 5.But how can I hide the error when the user starts typing in the input field even though there is only 1 character.
So In conclusion I only want to show error when the user stops typing in input field and when the length of password input is less than 5
function validate(){
var password = document.getElementById('demo2')
var error2= document.getElementById('error2')
var flag =true;
if(password.value.trim()==""){
// alert('blank password')
password.style.border="dotted red"
password.style.outline="none"
error2.innerHTML ='***Enter Password'
flag=false
}else if(password.value.trim()!=""){
password.style.border=""
}
if( password.value.length < 5){
error2.innerHTML ='***Password too short'
flag = false;
}
else if(password.value.length >= 5){
error2.innerHTML = ''
flag = true;
}
// alert(flag);
return flag // to maintain state of flag
}
<form onsubmit="return validate();">
<label for="">Password</label>
<p id="error2"></p>
<input type="text"name="input2" id="demo2" oninput="return validate();">
<input type="submit" name="input3" id="demo3">
</form>
let timeout;
function typeFinished() {
timeout = setTimeout(validate, 2000);
}
function validate(){
var password = document.getElementById('demo2')
var error2= document.getElementById('error2')
var flag =true;
if(password.value.trim()==""){
// alert('blank password')
password.style.border="dotted red"
password.style.outline="none"
error2.innerHTML ='***Enter Password'
flag=false
}else if(password.value.trim()!=""){
password.style.border=""
}
if( password.value.length < 5){
error2.innerHTML ='***Password too short'
flag = false;
}
else if(password.value.length >= 5){
error2.innerHTML = ''
flag = true;
}
// alert(flag);
return flag // to maintain state of flag
}
<form onsubmit="return validate();">
<label for="">Password</label>
<p id="error2"></p>
<input type="text"name="input2" id="demo2" oninput="return typeFinished();">
<input type="submit" name="input3" id="demo3">
</form>
I used onkeyup() to hide error when user starts typing but is shown after 4 secs if the password is less than 5 characters and inside the onkeyup() function I used setTimeout(validate,4000) function to call the validate function thus the validate function is called after 4secs and once the length is greater than 5 the error is hidden and validate function won't run
function validate(){
var password = document.getElementById('demo2')
var error2= document.getElementById('error2')
var flag =true;
if(password.value.trim()==""){
// alert('blank password')
password.style.border="dotted red"
password.style.outline="none"
error2.innerHTML ='***Enter Password'
flag=false
}else if(password.value.trim()!=""){
password.style.border=""
}
if( password.value.length < 5){
error2.innerHTML ='***Password too short'
flag = false;
}
else if(password.value.length >= 5){
error2.innerHTML = ''
flag = true;
}
// alert(flag);
return flag // to maintain state of flag
}
function fun3(){
var error2= document.getElementById('error2')
error2.innerHTML=''
setTimeout(validate,4000)
}
<form onsubmit="return validate();">
<label for="">Password</label>
<p id="error2"></p>
<input type="text"name="input2" id="demo2" oninput="return validate();"onkeyup=fun3();>
<input type="submit" name="input3" id="demo3"">
</form>
I am trying to show a loader in the google sheets sidebar on the button click either on the complete page or at least on the button so that users submitting the form should not press again until the earlier form is submitted. I have added loader with support from #Tanaike in this question. Although that works in some pages that have fewer and simple components but it fails to work in the page with more and complex components like multi-select with dynamic values that are fetched from sheet, adding/removing multiple inputs, multistep form, etc, and throws error in the console of the browser Uncaught TypeError: google.script.withSuccessHandler is not a function at copyFiles (userCodeAppPanel:91:23) at HTMLButtonElement.onclick (userCodeAppPanel:1:1). I am wondering if I could make the one answered in the above-mentioned question work on this complex page as well.
[] [1]
complete HTML code with all components:
<body onload="addList()">
<div id="loader" class="loader" style="display:none;">
<div class="loadingio-spinner-spinner-u1f174wamc"><div class="ldio-43p7dnbmew6">
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div></div>
</div>
<form id="regForm" style="padding-top:0px;">
<div class="steps">
<div class="step"></div>
<div class="first_step_content">Copy FIles</div>
<div class="step_line"></div>
<div class="step"></div>
<div class="second_step_content">Select Members</div>
</div>
<div class="tab">
<div>
<input list="dropdownList" name="list" placeholder="Choose Client" id="clientname" required class="client_list"> <!-- Modified -->
<datalist id="dropdownList"> <!-- Dynamic list of clients --> </datalist>
</div>
<div id="files">
<? var innerHTML= createInnerHTML(); ?>
<select name="langOpt[]" multiple id="langOpt" aria-label="JOINT" aria-required="true" required="">
<!-- <option value=""></option> -->
<? innerHTML.forEach(function(option) { ?>
<option class="<?= option.clas ?> post" value="<?= option.value ?>"><?= option.text ?></option>
<? }); ?>
</select>
</div>
</div>
<div class="tab">
<div>
<label for="List">Select Client:</label><br>
<input list="dropdownList" name="list" placeholder="Choose Client" id="clientname" required class="client_list" onkeyup="myFunction()" > <!-- Modified -->
<datalist id="dropdownList"> <!-- Dynamic list of clients --> </datalist>
</div>
<div id="editors">
<!-- Writers -->
<label for="List">Select Writers</label><br>
<? var innerHTML= writer_list(); ?>
<select name="writers[]" multiple id="writers" aria-label="JOINT" aria-required="true" required="">
<!-- <option value=""></option> -->
<? innerHTML.forEach(function(option) { ?>
<option class="<?= option.clas ?> post" value="<?= option.value ?>"><?= option.text ?></option>
<? }); ?>
</select>
</div>
<label>Share with Others</label>
<div class="field_wrapper">
<div>
<input type="text" name="field_name[]" value="" placeholder="example#gmail.com" style="width: 68%;"/>
<ion-icon name="add-outline" class="icon"></ion-icon>
</div>
</div>
</div>
<!-- <input type="button" value="Add templates" id="btn"> -->
<div style="overflow:auto;">
<div style="align-items: center; align-content: center; text-align: center; margin-top: 30px;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<script>
$('#langOpt').multiselect({
columns: 1,
placeholder: 'Select Templates',
search: true,
selectAll: true,
// id: 'temp',
});
$('#writers').multiselect({
columns: 1,
placeholder: 'Select Writers',
search: true,
selectAll: true,
// id: 'temp',
});
// Creates the dynamic input Fields
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value="" style="width: 68%;"/><ion-icon name="remove-outline" class="icon"></ion-icon></div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
// The function that runs on button click
function copyFiles() {
const button = document.getElementById("btn");
button.innerHTML = "Copying..";
button.setAttribute('disabled', 'disabled');
document.getElementById("loader").style.display = "block";
var tempid = [];
var tempname = [];
$('#files input:checked').each(function() {
tempid.push($(this).attr('value'));
tempname.push($(this).attr('title'));
});
var email = [];
$('#editors input:checked').each(function() {
email.push($(this).attr('value'));
});
var input_array= $("input[name='field_name[]']").map(function copyFiles() {
return this.value;
}).get();
var emails = [...email, ...input_array];
console.log(emails)
// client Name
var name = document.getElementById('clientname');
var client_name = name.value;
// var folder_url = name.title;
google.script.withSuccessHandler(_ => {
// Please set the loading animation here.
// In this sample modification, when the button is clicked, the button is disabled, when Google Apps Script is finished, the button is enabled.
document.getElementById("loader").style.display = "none";
button.removeAttribute('disabled');
button.innerHTML = "Add";
}).run.copy_files(tempid, tempname, client_name, emails);
document.getElementById('clientname').value=''; //ms-options-wrap
for (var checkbox of markedCheckbox) {
checkbox.checked = false;
}
markedCheckbox.checked = false;
}
</script>
</form>
<script type="module" src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.esm.js"></script>
<script nomodule src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.js"></script>
<script>
// Multi step form
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 = "Copy Files";
document.getElementById("nextBtn").setAttribute('id', 'btn');
document.getElementById("btn").setAttribute('onclick', 'copyFiles()');
// document.getElementById("btn").removeAttribute('onclick')
} else {
document.getElementById("btn").innerHTML = "Next";
document.getElementById("btn").setAttribute('id', 'nextBtn');
document.getElementById("nextBtn").setAttribute('onclick', 'nextPrev(1)');
}
//... and run a function that will display 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...
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// 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 = true;
}
}
// 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 on the current step:
x[n].className += " active";
}
</script>
</body>
<script>
function addList() {
google.script.run
.withFailureHandler(onFailure)
.withSuccessHandler(addListValues)
.getList();
}
function addListValues(values) {
var list = document.getElementById('dropdownList');
var temp_name = values.value;
var url_link = values.url_link;
for (var i = 0; i < temp_name.length; i++) {
var option = document.createElement("option"); // Modified
option.value = temp_name[i]; // Modified
option.title = url_link[i];
list.appendChild(option); // Modified
}
}
function onFailure(err) {
alert('There was an error!' + err.message);
}
Although this may be a long script to read and go through it. But helping me resolve it would mean a lot to me and I will be highly thank full to you. Thanks in advance.
Upon checking your code I saw a few typographical errors which are the following (see inline comments):
google.script.withSuccessHandler(_ => { //I think this should be google.script.run.withSuccessHandler
// Please set the loading animation here.
// In this sample modification, when the button is clicked, the button is disabled, when Google Apps Script is finished, the button is enabled.
document.getElementById("loader").style.display = "none";
button.removeAttribute('disabled');
button.innerHTML = "Add";
}).run.copy_files(tempid, tempname, client_name, emails);
Here are also three tags that seems to be inputted incorrectly:
<option class="<?= option.clas ?> post" value="<?= option.value ?>"><?= option.text ?></option>
This should be:
<option class="<?= option.class ?> post" value="<?= option.value ?>"><?= option.text ?></option>
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.
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>