Creating a Multi-Step questionnaire with HTML, JS, FLASK and MySQL - javascript

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>

Related

Take effect from step 1 to step 3 wizard

I'm currently using twitter bootstrap wizard as this template, so my wizard structure is something like this:
form
step1
checkbox
button next
step2
inputs
button next
step3
submit
The checkboxes are defined as:
#{
foreach (var test in #Html.GetEnumSelectList<length>())
{
<div class="form-check form-check-inline mb-3">
<input id="#test.Text" type="checkbox" value="#test.Value" name="selectedTest" class="form-check-input">
<label for="#test.Text" class="form-check-label">#test.Text</label>
</div>
}
}
So I want to get change step 3, style: none to style: block if one of these checkboxes is checked as:
<script>
let id;
$("input[type=checkbox]").on("change", function () {
id = $(this).attr("id");
const text = document.getElementById(id);
if ($(this).is(":checked")) {
text.style.display = "block";
}
else
{
text.style.display = "none";
const IsChecked = $("input[type=checkbox]");
let show = "none";
for (let i = 0; i < IsChecked.length; i++) {
if (IsChecked[i].checked) {
show = "block";
}
break;
}
}
})
</script>
But oh surprise, the HTML of step 3 is not available yet until I go to step 3, how can tell step 1 to do the change into step 3 when the checkbox of step 1 is checked?

Apps script: Show loader on button click in a form/page with components like dynamic drop downs, multiple inputs, etc

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>

Flask and JS: Unable to Submit Form

I'm having a issue submitting my form. I'm trying to a make a multi-step form with Flask and bit of JS. The basic HTML structure of the form is:
<form id="regForm" action="{{ url_for("index")}}" method="post" enctype="multipart/form-data">
<div class="tab"> <!--Some fields--> </div>
<div class="tab"> <!--Some fields--> </div>
<div class="tab"> <!--Some fields--> </div>
<div class="tab"> <!--Some fields--> </div>
<!--Buttons to change tabs-->
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
The nextPrev() functions are in a file called scripts.js. This is directly from a W3 schools example. It is as follows:
var currentTab = 0;
showTab(currentTab);
function showTab(n) {
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
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";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
fixStepIndicator(n)
}
function nextPrev(n) {
var x = document.getElementsByClassName("tab");
if (n == 1 && !validateForm()) return false;
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
document.getElementById("regForm").submit();
return false;
}
showTab(currentTab);
}
The document.getElementById("regForm").submit(); line should be submitting the form, since I see the button text changing to 'Submit' on the last slide. This isn't submitting it to my app though. The app looks for a POST request to / .
from flask import Flask, request, render_template, redirect, url_for
import os
def create_app():
app = Flask(__name__)
assets._named_bundles = {}
register_extensions(app)
#app.route("/", methods =["GET", "POST"])
def index():
if request.method == "POST":
# Do a bunch of stuff
return render_template("index.html")
Why is this not sending a request to my Python script?
The above code is minimal, I've uploaded a gist with the full code for Flask, JS, HTML.
I've created a codesandbox with my code here, you can also view the form itself here.
Have you added csrf_protection in your app?
If you did, Then do csrf.protection.exempt()

Coding beginner needing assistance

I'm brand new to coding. I've created a form with three fields- two with "number" types and one with radio button selection. I'm trying to utilize "try catch throw" to validate these fields and have error messages echoed onto the screen (not as an alert). I know that there is a lot of code in here, but I am really lost with this. Here is my HTML and js:
HTML:
<form>
<fieldset>
<label for="hshld" class="formhdr">Total number of people in your household:</label>
<input type="number" id="hshld" name="hshld" min="1">
</fieldset>
<fieldset>
<label for="hrrisk" class="formhdr">Number of high-risk people in your household:</label>
<input type="number" id="hrrisk" name="hrrisk" min="0">
</fieldset>
<fieldset>
<legend class="formhdr">Number of weeks in isolation:</legend>
<input type="radio" id="countone" name="headcount">
<label for="countone" class="numweeks">1</label>
<input type="radio" id="counttwo" name="headcount">
<label for="counttwo" class="numweeks">2</label>
<input type="radio" id="countthree" name="headcount">
<label for="countthree" class="numweeks">3</label>
<input type="radio" id="countfour" name="headcount">
<label for="countfour" class="numweeks">4+</label>
</fieldset>
<input type="submit" value="Submit" id="submit">
</form>
and my .js:
//Global variables
var hshld = document.getElementById("hshld");
var mysubmit = document.getElementById("submit");
var radioError = document.getElementById("radioError");
var weekCount;
//this function checks to see if the user entered a number into the field
function validatehshld() {
try {
if (hshld.value == "") {
throw "Enter a number!";
}
hshld.style.outline = "none";
// clear input box
}
catch (hshldError) {
hshld.style.outline = "2.5px dashed red";
hshld.placeholder = hshldError;
return false;
}
}
// makes sure that the radio button is selected. If not, throws an error message into the "radioError" paragraph at under the form.
function validatewkCount() {
try {
if (weekCount == 0) {
throw document.getElementById('radioError').innerHTML = "Select a number!";
}
// clear input box
hshld.style.outline = "none";
}
catch (weekCountError) {
radioError.style.outline = "2.5px dashed red";
radioError.placeholder = radioError;
return false;
}
}
// stop the form from submitting if a field needs attention
function endEvent() {
return event.preventDefault();
}
function validateSubmit() {
if(validatehshld() === false && validatewkCount() === false) {
endEvent();
}
}
// EventListeners, includes IE8 compatibility
if (hshld.addEventListener) {
hshld.addEventListener("focusout", validatehshld, false);
} else if (hshld.attachEvent) {
hshld.attachEvent("onclick", validatehshld);
}
// runs validateSubmit() function when the user clicks the submit button
if (mysubmit.addEventListener) {
mysubmit.addEventListener("click", validateSubmit, false);
} else if (mysubmit.attachEvent) {
mysubmit.attachEvent("onclick", validateSubmit);
}
if (mysubmit.addEventListener) {
mysubmit.addEventListener("click", numBottles, false);
} else if (mysubmit.attachEvent) {
mysubmit.attachEvent("onclick", numBottles);
}
// this function gets called via the onclick attribute (line 44)
function numBottles() {
// takes the current value of the input field from id "hshld"
var people = document.getElementById("hshld").value;
var hrrisk = document.getElementById("hrrisk").value;
// this variable represents the number of gallons a single person should have for one week of isolation- 1 gallon per day
var weekWater = 7;
// this variable will hold the number of weeks selected from the radio buttons
var weekCount;
// this code determines which radio button is selected and assigns a value to the variable depending on which radio button is selected
if (document.getElementById('countone').checked) {
var weekCount = 1;
} else if (document.getElementById('counttwo').checked) {
var weekCount = 2;
} else if (document.getElementById('countthree').checked) {
var weekCount = 3;
} else if (document.getElementById('countfour').checked) {
var weekCount = 4;
} else if (isNaN(weekCount) === true) {
var weekCount = 0;
}
// echo out the calculation (people X weekWater) to the span object with id=bottles
document.getElementById("bottles").innerHTML = (people * weekWater * weekCount) + (hrrisk * weekCount);
}
Try not to use try, catch, or throw here, instead create your error message in a new element and place it in the html somewhere you think it looks nice.
I would just use:
if (typeof hshld.value !== 'number') { // if a wrong data type was entered
document.getElementById("error-zone").innerHTML += "<div>Enter a number!</div"
} else {
// continue calculating answer
}
for the quick and dirty method.

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
}

Categories

Resources