Create a New onclick function for each element created - javascript

I am building a website that takes in unique information (such as shareholder info and loan info) about specific store clients and stores them.
Because it is impossible to know how many shareholders/lenders a client has, the website has the ability to add and remove shareholders/Lenders and toggle between them being legal entities or individuals.
My issue:
My issue is that when I add a shareholder/Lender, the radio toggle (which is an onclick) function does not seem to work properly as I add new shareholders/lenders.
Is there a way to add shareholders/lenders (by cloning) while updating the onclick functions for each created shareholder?
I have replicated my code below in a JS fiddle:
Client Project
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="aa.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="aa.js" defer></script>
<title>Loan Agreement</title>
</head>
<body>
<form action="#" class="form">
<h1 class="text-center">Client Registration List</h1>
<!-- Progress bar -->
<div class="progressbar">
<div class="progress" id="progress"></div>
<div class="progress-step progress-step-active" data-title="Client Info"></div>
<div class="progress-step" data-title="Shareholder Info"></div>
<div class="progress-step" data-title="Loan Info"></div>
<div class="progress-step" data-title="Background"></div>
<div class="progress-step" data-title="Defs"></div>
</div>
<!-- Steps -->
<div class="form-step form-step-active">
<div class="checkbox">
<label for="legalEntity">Legal Entity</label>
<input type="radio" name="choice" id="legalEntity" value="legalEntity" onclick="filterForm()" checked />
<label for="Individual">Individual</label>
<input type="radio" name="choice" id="Individual" value="Individual" onclick="filterForm()" />
</div>
<div id="lec" class="legal-entity-content">
<div class="input-group">
<label for="CompanyName">Company Name</label>
<input type="text" name="CompanyName" id="CompanyName" placeholder="Ex. My Pocket Counsel" />
</div>
<div class="input-group">
<label for="RegisteredAddress">Registered Address</label>
<input type="text" name="RegisteredAddress" id="RegisteredAddress" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="RegistrationNumber">Registration Number</label>
<input type="text" name="RegistrationNumber" id="RegistrationNumber" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="Definedas">Defined as...</label>
<input type="text" name="Definedas" id="Definedas" placeholder="Ex. MyPocketCounsel" />
</div>
</div>
<div id="ic" class="individual-content hide">
<div class="input-group">
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="LastName">Last Name</label>
<input type="text" name="LastName" id="LastName" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="Address">Address</label>
<input type="text" name="Address" id="Address" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="Definedas">Defined as...</label>
<input type="text" name="Definedas" id="Definedas" placeholder="Ex. MyPocketCounsel" />
</div>
</div>
<div class="">
Next
</div>
</div>
<div class="form-step">
<div id="readroot">
<div class="checkbox">
<label for="LegalEntity">Legal Entity</label>
<input type="radio" name="choice0" id="legalEntity0" value="legalEntity" onclick="filterForm0()" />
<label for="Individual">Individual</label>
<input type="radio" name="choice0" id="Individual0" value="Individual" onclick="filterForm0()" />
</div>
<div id="lec0" class="legal-entity-content">
<div class="input-group">
<label for="CompanyName">Company Name</label>
<input type="text" name="CompanyName" id="CompanyName" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="RegisteredAddress">Registered Address</label>
<input type="text" name="RegisteredAddress" id="RegisteredAddress" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="RegistrationNumber">Registration Number</label>
<input type="text" name="RegistrationNumber" id="RegistrationNumber" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="Definedas">Defined as...</label>
<input type="text" name="Definedas" id="Definedas" placeholder="Ex. MyPocketCounsel" />
</div>
</div>
<div id="ic0" class="individual-content hide">
<div class="input-group">
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="LastName">Last Name</label>
<input type="text" name="LastName" id="LastName" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="Address">Address</label>
<input type="text" name="Address" id="Address" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="Definedas">Defined as...</label>
<input type="text" name="Definedas" id="Definedas" placeholder="Ex. MyPocketCounsel" />
</div>
</div>
<input type="button" value="Remove Lender" class="btn btn-remove-lender"
onclick="if (counter >= 1){
counter --;
this.parentNode.parentNode.removeChild(this.parentNode);
}else{alert('you must have at least one Lender');}">
</div>
<div>
<div class="checkbox">
<label for="LegalEntity">Legal Entity</label>
<input type="radio" name="choice2" id="legalEntityX" value="legalEntityX" onclick="filterFormX()" />
<label for="Individual">Individual</label>
<input type="radio" name="choice2" id="IndividualX" value="IndividualX" onclick="filterFormX()" />
</div>
<div id="lecX" class="legal-entity-content">
<div class="input-group">
<label for="CompanyName">Company Name</label>
<input type="text" name="CompanyName" id="CompanyName" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="RegisteredAddress">Registered Address</label>
<input type="text" name="RegisteredAddress" id="RegisteredAddress" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="RegistrationNumber">Registration Number</label>
<input type="text" name="RegistrationNumber" id="RegistrationNumber" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="Definedas">Defined as...</label>
<input type="text" name="Definedas" id="Definedas" placeholder="Ex. MyPocketCounsel" />
</div>
</div>
<div id="icX" class="individual-content hide">
<div class="input-group">
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" placeholder="Ex.MyPocketCounsel" />
</div>
<div class="input-group">
<label for="LastName">Last Name</label>
<input type="text" name="LastName" id="LastName" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="Address">Address</label>
<input type="text" name="Address" id="Address" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="Definedas">Defined as...</label>
<input type="text" name="Definedas" id="Definedas" placeholder="Ex. MyPocketCounsel" />
</div>
</div>
<input type="button" value="Remove Lender" class="btn btn-remove-lender"
onclick="if (counter >= 1){
counter --;
this.parentNode.parentNode.removeChild(this.parentNode);
}else{alert('you must have at least one Lender');}">
</div>
<span id="writeroot" class="pls"></span>
<div class="btns-group">
<input type="button" id="morefields" value="Add Lender" class="btn btn-add-lender" onclick="moreFields()">
Previous
Next
</div>
<!--
"₦"
-->
</div>
<div class="form-step">
<div class="input-group">
<label for="LoanAmount">Loan Amount</label>
<div class="wrapper">
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon currency-symbol">$</div>
<input type="text" class="form-control currency-amount" id="inlineFormInputGroup" placeholder="0.00" size="8">
<div class="input-group-addon currency-addon">
<select class="currency-selector">
<option data-symbol="$" data-placeholder="0.00">USD</option>
<option data-symbol="€" data-placeholder="0.00">EUR</option>
<option data-symbol="£" data-placeholder="0.00">GBP</option>
<option data-symbol="₦" data-placeholder="0.00" selected>NGN</option>
<option data-symbol="¥" data-placeholder="0">JPY</option>
<option data-symbol="$" data-placeholder="0.00">CAD</option>
<option data-symbol="$" data-placeholder="0.00">AUD</option>
</select>
</div>
</div>
</div>
</div>
<div class="input-group">
<label for="Moratorium">Moratorium</label>
<input type="text" name="Moratorium" id="Moratorium" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="InterestRate">Interest Rate</label>
<input type="text" name="InterestRate" id="InterestRate" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="LoanDuration">Loan Duration/Maturity Date</label>
<input type="text" name="LoanDuration" id="LoanDuration" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="input-group">
<label for="UseofLoan">Use of Loan</label>
<input type="text" name="UseofLoan" id="UseofLoan" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="">
<div class="btns-group">
Previous
Next
</div>
</div>
</div>
<div class="form-step">
<div class="input-group">
<label for="Recitals">Recitals</label>
<input type="text" name="Recitals" id="Recitals" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="">
<div class="btns-group">
Add Recital
Remove Recital
Previous
Next
</div>
</div>
</div>
<div class="form-step">
<div class="input-group">
<label for="Definitions">Definitions</label>
<input type="text" name="Definitions" id="Definitions" placeholder="Ex. MyPocketCounsel" />
</div>
<div class="">
<div class="btns-group">
Add Definition
Remove Definition
Previous
<input type="submit" value="Submit" class="btn" />
</div>
</div>
</form>
</body>
</html>
Javascript:
const prevBtns = document.querySelectorAll(".btn-prev");
const nextBtns = document.querySelectorAll(".btn-next");
const progress = document.getElementById("progress");
const formSteps = document.querySelectorAll(".form-step");
const progressSteps = document.querySelectorAll(".progress-step");
let formStepsNum = 0;
nextBtns.forEach((btn) => {
btn.addEventListener("click", () => {
formStepsNum++;
updateFormSteps();
updateProgressbar();
});
});
prevBtns.forEach((btn) => {
btn.addEventListener("click", () => {
formStepsNum--;
updateFormSteps();
updateProgressbar();
});
});
function updateFormSteps() {
formSteps.forEach((formStep) => {
formStep.classList.contains("form-step-active") &&
formStep.classList.remove("form-step-active");
});
formSteps[formStepsNum].classList.add("form-step-active");
}
function updateProgressbar() {
progressSteps.forEach((progressStep, idx) => {
if (idx < formStepsNum + 1) {
progressStep.classList.add("progress-step-active");
} else {
progressStep.classList.remove("progress-step-active");
}
});
const progressActive = document.querySelectorAll(".progress-step-active");
progress.style.width =
((progressActive.length - 1) / (progressSteps.length - 1)) * 100 + "%";
}
const IndividualContent = document.getElementById("ic");
IndividualContent.classList.add("hide");
function filterForm() {
if(document.getElementById('legalEntity').checked) {
//hide individual contnet
const IndividualContent = document.getElementById("ic");
IndividualContent.classList.add("hide");
const legalEntityContent = document.getElementById("lec");
legalEntityContent.classList.remove("hide");
}else {
const legalEntityContent = document.getElementById("lec");
legalEntityContent.classList.add("hide");
const IndividualContent = document.getElementById("ic");
IndividualContent.classList.remove("hide");
}
}
function filterFormX() {
if(document.getElementById('legalEntityX').checked) {
//hide individual contnet
const IndividualContent = document.getElementById("icX");
IndividualContent.classList.add("hide");
const legalEntityContent = document.getElementById("lecX");
legalEntityContent.classList.remove("hide");
}else {
const legalEntityContent = document.getElementById("lecX");
legalEntityContent.classList.add("hide");
const IndividualContent = document.getElementById("icX");
IndividualContent.classList.remove("hide");
}
}
//Function to get more Lenders ie. input fields
let counter = 0;
let idCounter =0;
//old count once we get to the
let OC = idCounter -1;
function moreFields() {
var x, i;
counter ++;
idCounter ++;
//old count
let OC = idCounter -1;
//change function name
document.getElementById('legalEntity'+OC).onclick= filterForm1;
document.getElementById('Individual'+OC).onclick= filterForm1;
//let insertHere = document.getElementById('writeroot');
let newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
console.log(OC);
document.getElementById('legalEntity'+OC).id = 'legalEntity'+idCounter;
document.getElementById('Individual'+OC).id = 'Individual'+idCounter;
document.getElementById('ic'+OC).id = 'ic'+idCounter;
document.getElementById('lec'+OC).id = 'lec'+idCounter;
let insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
//Function to toggle legal entity for Lender2
function filterForm0() {
if(document.getElementById('legalEntity0').checked) {
//hide individual contnet
const IndividualContent = document.getElementById("ic0");
IndividualContent.classList.add("hide");
const legalEntityContent = document.getElementById("lec0");
legalEntityContent.classList.remove("hide");
console.log('nope');
}else {
const legalEntityContent = document.getElementById("lec0");
legalEntityContent.classList.add("hide");
const IndividualContent = document.getElementById("ic0");
IndividualContent.classList.remove("hide");
console.log('bange');
}
}
//Function to toggle legal entity for Lender3
function filterForm1() {
if(document.getElementById('legalEntity1').checked) {
//hide individual contnet
const IndividualContent = document.getElementById("ic1");
IndividualContent.classList.add("hide");
const legalEntityContent = document.getElementById("lec1");
legalEntityContent.classList.remove("hide");
console.log('nope2');
}else {
const legalEntityContent = document.getElementById("lec1");
legalEntityContent.classList.add("hide");
const IndividualContent = document.getElementById("ic1");
IndividualContent.classList.remove("hide");
console.log('bange2');
}
}
function showContent() {
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
}
function updateSymbol(e){
var selected = $(".currency-selector option:selected");
$(".currency-symbol").text(selected.data("symbol"));
$(".currency-amount").prop("placeholder", selected.data("placeholder"));
$('.currency-addon-fixed').text(selected.text());
}
$(".currency-selector").on("change", updateSymbol);
updateSymbol();

Related

get multiple form values as an array of object using a single click

I have multiple forms in a div. I would like to get the values of each form as an array of object in a single click.
<form data-category="1">
<div class="form-group">
<label for="usr">First Name:</label>
<input type="text" class="form-control" id="usr" name="username" />
</div>
<div class="form-group">
<label for="pwd">Last Name:</label>
<input type="text" class="form-control" id="pwd" name="lname" />
</div>
</form>
<form data-category="2">
<div class="form-group">
<label for="usr">Name:</label>
<input type="text" class="form-control" id="usr" name="username" />
</div>
<div class="form-group">
<label for="usr">Age:</label>
<input type="number" class="form-control" id="usr" name="age" />
</div>
<div>
<p>Gender></p>
<div class="form-check">
<label class="form-check-label">
<input
type="radio"
class="form-check-input"
name="optradio"
/>Male
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input
type="radio"
class="form-check-input"
name="optradio"
/>Female
</label>
</div>
</div>
</form>
<button type="submit" class="btn btn-primary">Submit</button>
I would like to get the result where exh object has a key called form whose value is the form number and the another key called inputdata which is an object whose keys represnt the input numbers and value are input values:
[{
form:1,
inputdata:{1:"John",2:"John Doe"}
},
{
form:2,
inputdata:{1:"Jane",2:25,3:"female"}
}]
You can probably do the following:
One other option can be to serialize the form data and then get the value of form, but this would work as well
const form = document.querySelectorAll('form');
function submitForm() {
const data = [];
for(let i=0; i<form.length; i++) {
const elements = form[i].elements;
data.push({form: form[i].getAttribute('data-category'), inputData: {}});
for(let j=0; j<elements.length; j++) {
if(elements[j].type !== 'radio') {
data[i].inputData[[elements[j].name]] = elements[j].value;
} else {
if(elements[j].checked) {
data[i].inputData[[elements[j].name]] = elements[j].value;
}
}
}
}
console.log(data);
}
<form data-category="1">
<div class="form-group">
<label for="usr">First Name:</label>
<input type="text" class="form-control" id="usr" name="firstName" />
</div>
<div class="form-group">
<label for="pwd">Last Name:</label>
<input type="text" class="form-control" id="pwd" name="lastName" />
</div>
</form>
<form data-category="2">
<div class="form-group">
<label for="usr">Name:</label>
<input type="text" class="form-control" id="usr" name="firstName" />
</div>
<div class="form-group">
<label for="usr">Age:</label>
<input type="number" class="form-control" id="usr" name="age" />
</div>
<div>
<p>Gender></p>
<div class="form-check">
<label class="form-check-label">
<input
type="radio"
class="form-check-input"
name="gender"
value="M"
/>Male
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input
type="radio"
class="form-check-input"
name="gender"
valeu="F"
/>Female
</label>
</div>
</div>
</form>
<button type="submit" class="btn btn-primary" onclick="submitForm()">Submit</button>
You may use FormData and Object.fromEntries to get the form data easily like below:
const btn = document.querySelector("#submit");
btn.addEventListener("click", () => {
const forms = document.querySelectorAll("form");
const output = [];
forms.forEach(form => {
output.push({
form: form.dataset.category,
inputData: Object.fromEntries(new FormData(form)),
});
});
console.log(output);
});
<!DOCTYPE html>
<html lang="en">
<head> </head>
<body>
<form data-category="1">
<div class="form-group">
<label for="usr">First Name:</label>
<input
type="text"
class="form-control"
id="usr"
name="username"
/>
</div>
<div class="form-group">
<label for="pwd">Last Name:</label>
<input type="text" class="form-control" id="pwd" name="lname" />
</div>
</form>
<form data-category="2">
<div class="form-group">
<label for="usr">Name:</label>
<input
type="text"
class="form-control"
id="usr"
name="username"
/>
</div>
<div class="form-group">
<label for="usr">Age:</label>
<input type="number" class="form-control" id="usr" name="age" />
</div>
<div>
<p>Gender</p>
<div class="form-check">
<label class="form-check-label">
<input
type="radio"
class="form-check-input"
name="gender"
value="1"
/>Male
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input
type="radio"
class="form-check-input"
name="gender"
value="0"
/>Female
</label>
</div>
</div>
</form>
<button id="submit" type="button" class="btn btn-primary">
Submit
</button>
</body>
</html>

When I select one value from the dropdown button, the other values appear as well

I was wondering if you can help me out with the following. I created a dropdown payment option. When I select "checking/savings account" the form displays 2 input fields so that the user can type in their banking account number and router number. This is what I want for this option. However, when I select the credit card option, the credit card form appears, but the banking form appears on top of it. Can someone tell me what I am doing wrong? Also, when I switch options back and forth, the forms do not change at all, but remain the same.
document.getElementById('paymentOptions').onchange = function () {
if (this.value == 'CreditCard') {
document.getElementById('CreditCard').style.display = 'block'
} else {
document.getElementById('Banking').style.display = 'block';
}
}
<div class="col-75">
<div class="container">
<form>
<label>Payment method</label>
<select id="paymentOptions" name="paymentOptions">
<option value="CreditCard">Credit Card</option>
<option value="BankingAccount">Checking/Savings Account</option>
</select>
<div class="row" id="Banking" style="display: none">
<div class="col-50">
<label for="ccnum">Bank Account</label>
<input type="text" id="ccnum" name="cardnumber">
</div>
<div class="col-50">
<label for="ccnum">Routing Number</label>
<input type="text" id="ccnum" name="cardnumber">
</div>
</div>
<div class="row" id="CreditCard" style="display: none">
<div class="col-50">
<label for="fname"><i class="fa fa-user"></i> Company Name</label>
<input type="text" id="fname" name="firstname">
<label for="email"><i class="fa fa-envelope"></i> Email</label>
<input type="text" id="email" name="email">
<label for="adr"><i class="fa fa-address-card-o"></i> Address</label>
<input type="text" id="adr" name="address">
<label for="city"><i class="fa fa-institution"></i> City</label>
<input type="text" id="city" name="city">
<div class="row">
<div class="col-50">
<label for="state">State</label>
<input type="text" id="state" name="state">
</div>
<div class="col-50">
<label for="zip">Zip</label>
<input type="text" id="zip" name="zip">
</div>
</div>
</div>
<div class="col-50">
<label for="fname">Accepted Cards</label>
<div class="icon-container">
<i class="fa fa-cc-visa" style="color:navy;"></i>
<i class="fa fa-cc-amex" style="color:blue;"></i>
<i class="fa fa-cc-mastercard" style="color:red;"></i>
<i class="fa fa-cc-discover" style="color:orange;"></i>
</div>
<label for="cname">Name on Card</label>
<input type="text" id="cname" name="cardname">
<label for="ccnum">Credit card number</label>
<input type="text" id="ccnum" name="cardnumber">
<label for="expmonth">Exp Month</label>
<input type="text" id="expmonth" name="expmonth">
<div class="row">
<div class="col-50">
<label for="expyear">Exp Year</label>
<input type="text" id="expyear" name="expyear">
</div>
<div class="col-50">
<label for="cvv">CVV</label>
<input type="text" id="cvv" name="cvv">
</div>
</div>
</div>
</div>
<p>
<input type="checkbox" id="autopayment" />
<label for="autopayment">Enroll in autopayment</label>
</p>
<input type="submit" value="Submit payment" class="btn">
</form>
</div>
</div>
</div>
You have to hide the other value when that one is selected in other words toggling
document.getElementById('paymentOptions').onchange = function() {
if (this.value == 'CreditCard') {
document.getElementById('CreditCard').style.display = 'block'
document.getElementById('Banking').style.display = 'none'
} else {
document.getElementById('Banking').style.display = 'block';
document.getElementById('CreditCard').style.display = 'none'
}
}
The reason for the problems you are getting is that you change the display of your CreditCard div and Banking div to block but you do not change them back to display: none if they are not chosen.
Also you should add an onload listener to check what the initial value of your paymentOptions dropdown is to then change the display value of your 2 divs.
window.onload = () => {
const paymentOptionsSelect = document.getElementById("paymentOptions");
const selectedOption = paymentOptionsSelect.options[paymentOptionsSelect.selectedIndex].value;
if (selectedOption == 'CreditCard') {
document.getElementById('CreditCard').style.display = 'block'
document.getElementById('Banking').style.display = 'none';
}
else {
document.getElementById('Banking').style.display = 'block';
document.getElementById('CreditCard').style.display = 'none'
}
};
Look carefully at the 2 added lines in your change listener:
document.getElementById('paymentOptions').onchange = function () {
if (this.value == 'CreditCard') {
document.getElementById('CreditCard').style.display = 'block'
document.getElementById('Banking').style.display = 'none'; // set back to display none when CreditCard is not selected.
} else {
document.getElementById('Banking').style.display = 'block';
document.getElementById('CreditCard').style.display = 'none' // set back to display none when Banking is not selected.
}
}
Good luck!
Try with Jquery 3.3.1 approach, Hoping this can help you
$(document).ready(function(){
$("#paymentOptions").on('change', function(){
if ($(this).val() == 'CreditCard') {
$('#CreditCard').css('display','block');
$('#CreditCard').css('display','none');
} else {
$('#CreditCard').css('display','none');
$('#CreditCard').css('display','block');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-75">
<div class="container">
<form>
<label>Payment method</label>
<select id="paymentOptions" name="paymentOptions">
<option value="CreditCard">Credit Card</option>
<option value="BankingAccount">Checking/Savings Account</option>
</select>
<div class="row" id="Banking" style="display: none">
<div class="col-50">
<label for="ccnum">Bank Account</label>
<input type="text" id="ccnum" name="cardnumber">
</div>
<div class="col-50">
<label for="ccnum">Routing Number</label>
<input type="text" id="ccnum" name="cardnumber">
</div>
</div>
<div class="row" id="CreditCard" style="display: none">
<div class="col-50">
<label for="fname"><i class="fa fa-user"></i> Company Name</label>
<input type="text" id="fname" name="firstname">
<label for="email"><i class="fa fa-envelope"></i> Email</label>
<input type="text" id="email" name="email">
<label for="adr"><i class="fa fa-address-card-o"></i> Address</label>
<input type="text" id="adr" name="address">
<label for="city"><i class="fa fa-institution"></i> City</label>
<input type="text" id="city" name="city">
<div class="row">
<div class="col-50">
<label for="state">State</label>
<input type="text" id="state" name="state">
</div>
<div class="col-50">
<label for="zip">Zip</label>
<input type="text" id="zip" name="zip">
</div>
</div>
</div>
<div class="col-50">
<label for="fname">Accepted Cards</label>
<div class="icon-container">
<i class="fa fa-cc-visa" style="color:navy;"></i>
<i class="fa fa-cc-amex" style="color:blue;"></i>
<i class="fa fa-cc-mastercard" style="color:red;"></i>
<i class="fa fa-cc-discover" style="color:orange;"></i>
</div>
<label for="cname">Name on Card</label>
<input type="text" id="cname" name="cardname">
<label for="ccnum">Credit card number</label>
<input type="text" id="ccnum" name="cardnumber">
<label for="expmonth">Exp Month</label>
<input type="text" id="expmonth" name="expmonth">
<div class="row">
<div class="col-50">
<label for="expyear">Exp Year</label>
<input type="text" id="expyear" name="expyear">
</div>
<div class="col-50">
<label for="cvv">CVV</label>
<input type="text" id="cvv" name="cvv">
</div>
</div>
</div>
</div>
<p>
<input type="checkbox" id="autopayment" />
<label for="autopayment">Enroll in autopayment</label>
</p>
<input type="submit" value="Submit payment" class="btn">
</form>
</div>
</div>
</div>

If text boxes are not empty check checkbox

I am trying to figure out how to check if all 4 inputs are filled out then checkmark the contact information check box. If any are not filled out uncheck the checkbox.
Any help with this would be greatly appreciated.
$(document).on('change', '#ContactName, #ContactEmail, #ContactPhone', function() {
if ('#ContactName, #ContactEmail, #ContactPhone' === '') {
$("#contactinformation").prop("checked", false);
} else {
$("#contactinformation").prop("checked", true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="row">
<div class="col-lg-7">
<div class="form-group">
<label for="ContactName">Contact name:</label>
<input type="text" class="form-control input-sm" name="ContactName" id="ContactName" size="40" maxlength="120" value="" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-7">
<div class="form-group">
<label for="BusinessName">Business name:</label>
<input type="text" class="form-control input-sm" name="BusinessName" id="BusinessName" size="40" maxlength="120" value="" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-7">
<div class="form-group">
<label for="ContactEmail">Email address:</label>
<input type="text" class="form-control input-sm" name="ContactEmail" id="ContactEmail" size="40" maxlength="80" value="" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-7">
<div class="form-group">
<label for="ContactPhone">Phone number (business hours):</label>
<input type="text" class="form-control input-sm" name="ContactPhone" id="ContactPhone" size="40" maxlength="50" value="" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<input type="checkbox" name="contactinformation" id="contactinformation" />
Contact information
</div>
</div>
</div>
Answer updated to reflect new requirement that BusinessName be optional.
See the comments inline:
// Set up a blur event handler for each text field
$('.form-control:not("#BusinessName")').on("blur", function(evt) {
let count = 0; // Keep track of how many are filled in
// Loop over all the text fields
$('.form-control:not("#BusinessName")').each(function(idx, el){
// If the field is not empty....
if(el.value !== ""){
count++; // Increase the count
}
});
// Test to see if all 3 are filled in
if(count === 3){
$("#contactinformation").prop("checked", true); // Check the box
} else {
$("#contactinformation").prop("checked", false); // Unheck the box
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="row">
<div class="col-lg-7">
<div class="form-group">
<label for="ContactName">Contact name:</label>
<input type="text" class="form-control input-sm" name="ContactName" id="ContactName" size="40" maxlength="120" value="" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-7">
<div class="form-group">
<label for="BusinessName">Business name:</label>
<input type="text" class="form-control input-sm" name="BusinessName" id="BusinessName" size="40" maxlength="120" value="" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-7">
<div class="form-group">
<label for="ContactEmail">Email address:</label>
<input type="text" class="form-control input-sm" name="ContactEmail" id="ContactEmail" size="40" maxlength="80" value="" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-7">
<div class="form-group">
<label for="ContactPhone">Phone number (business hours):</label>
<input type="text" class="form-control input-sm" name="ContactPhone" id="ContactPhone" size="40" maxlength="50" value="" />
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<input type="checkbox" name="contactinformation" id="contactinformation" disabled />
Contact information
</div>
</div>
</div>
Please try with below code snippet.
<input type="text" class="form-control input-sm InputText" name="BusinessName" id="BusinessName" size="40" maxlength="120" value="" />
$( document ).ready(function() {
$(".InputText").change(function(){
var checkCheckBox= true;
$(".InputText").each(function() {
if ($.trim($(this).val()) != '') {
checkCheckBox = false;
}
});
if (checkCheckBox == true)
{
$("#contactinformation").prop("checked",true);
}
else
{
$("#contactinformation").prop("checked",false);
}
});
});
Add "InputText" class in textbox, if you want to validate this thing.

input text field validation check

In login page i want to create form validation.
i wrote below mentioned code. but it does not work. i want to hide sign up button and show button when all the fields is not empty.
function signupbtnactive (){
var inputsignup = document.getElementsByClassName('input').val();
while(inputsignup != null && !inputsignup.isEmpty()) {
$('#signupbtn').show();
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sign-up-htm">
<div class="group">
<label for="newloginusername" class="label">Username</label>
<input id="newloginusername" type="text" class="input">
</div>
<div class="group">
<label for="newloginusersname" class="label">Surname</label>
<input id="newloginusersname" type="text" class="input">
</div>
<div class="group">
<label for="newloginuser" class="label">Loginname</label>
<input id="newloginuser" type="text" class="input">
</div>
<div class="group">
<label for="newloginpwd" class="label">Password</label>
<input id="newloginpwd" type="password" class="input" data-type="password">
</div>
<div class="group">
<label for="newloginpwdconfirm" class="label">Repeat Password</label>
<input id="newloginpwdconfirm" type="password" class="input" data-type="password">
</div>
<div class="group">
<label for="loginemail" class="label">Email Address</label>
<input id="loginemail" type="text" class="input">
</div>
<div class="group">
<label for="loginemailcopy" class="label">Repeat Email Address</label>
<input id="loginemailcopy" type="text" class="input">
</div>
<div class="group">
<label for="dobsignup" class="label">Date of birth</label>
<input id="dobsignup" type="text" class="input" onblur="Checkemailsignup()">
</div>
<div class="group" id="signupdivbtn">
<input type="submit" class="button" id="signupbtn" value="Sign Up" style="display: none;">
</div>
</div>
above mentioned dont work. please advice what is problem?
var inputsignup = document.getElementsByClassName('inputField') ;
This will return all elements with the specified class.So.You have to loop through the each element and check if the value is empty
function signupbtnactive (){
var inputsignup = document.getElementsByClassName('inputField') ;
var flag = false;
for(var i in inputsignup){
if(inputsignup[i].value== '' ){
flag = true;
}else{
//console.log(inputsignup[i].value);
}
}
if(!flag) {
$('#signupbtn').show();
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sign-up-htm">
<div class="group">
<label for="newloginusername" class="label">Username</label>
<input id="newloginusername" type="text" class="inputField">
</div>
<div class="group">
<label for="newloginusersname" class="label">Surname</label>
<input id="newloginusersname" type="text" class="inputField">
</div>
<div class="group">
<label for="newloginuser" class="label">Loginname</label>
<input id="newloginuser" type="text" class="inputField">
</div>
<div class="group">
<label for="newloginpwd" class="label">Password</label>
<input id="newloginpwd" type="password" class="inputField" data-type="password">
</div>
<div class="group">
<label for="newloginpwdconfirm" class="label">Repeat Password</label>
<input id="newloginpwdconfirm" type="password" class="inputField" data-type="password">
</div>
<div class="group">
<label for="loginemail" class="label">Email Address</label>
<input id="loginemail" type="text" class="inputField">
</div>
<div class="group">
<label for="loginemailcopy" class="label">Repeat Email Address</label>
<input id="loginemailcopy" type="text" class="inputField">
</div>
<div class="group">
<label for="dobsignup" class="label">Date of birth</label>
<input id="dobsignup" type="text" class="inputField" onblur="signupbtnactive()">
</div>
<div class="group" id="signupdivbtn">
<input type="submit" class="button" id="signupbtn" value="Sign Up" style="display: none;">
</div>
</div>
<script>
//Set up the event listener to check every input when one changes
$(".group input").change(checkInputs)
//function that checks all the inputs for values
function checkInputs() {
let $signUpButton = $("#signupbtn")
let $inputs = $(".group input")
let numOfEmptyInputs = $inputs.filter((i, input) => !input.value).length
if(numOfEmptyInputs === 0) {
$signUpButton.show()
} else {
$signUpButton.hide()
}
}
</script>

how to validate form in jquery [duplicate]

This question already has answers here:
A simple jQuery form validation script [closed]
(2 answers)
Closed 7 years ago.
When i submit the form alert will be show but after page is redirect.
i have call function to the submit button on click.
alert will show and after form will be submited
please give me idea to validate form
function companyFormValidation()
{
var name = document.getElementById('companyname').value;
var title = document.getElementById('companytitle').value;
var desc = document.getElementById('description').value;
var logo = document.getElementById('logo').value;
var email = document.getElementById('emailid').value;
var website = document.getElementById('siteurl').value;
var phonenumber = document.getElementById('phonenumber').value;
var faxNumber = document.getElementById('faxNumber').value;
var address = document.getElementById('address').value;
var latitude = document.getElementById('latitude').value;
var longitude = document.getElementById('longitude').value;
if(name == '')
{
alert('Name can not empty');
//$("#ename").html("Name can't be empty..");
}
}
<form id="addCompanyForm" method="post" action="#" class="form-horizontal" >
<fieldset>
<legend>Company </legend>
<div class="form-group">
<label class="col-lg-3 control-label">Name</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="companyname" id='companyname' />
<div id="ename"></div>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Title</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="companytitle" id="companytitle" />
<div id="etitle"></div>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Description</label>
<div class="col-lg-5">
<textarea class="form-control" name="description" id = "description"></textarea>
<div id="edesc"></div>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Logo</label>
<div class="col-lg-5">
<input type="file" class="form-control" name='logo' id="logo" >
<!-- <span class="input-group-btn">
<span class="btn btn-default btn-file">
Browse… <input type="file" name="">
</span>
</span> -->
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email </label>
<div class="col-lg-5">
<input type="text" class="form-control" name="emailid" id="emailid"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Website</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="siteurl" placeholder="http://" id="siteurl" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Phone number</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="phonenumber" id="phonenumber"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Fax number</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="faxNumber" id="faxNumber" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Address</label>
<div class="col-lg-5">
<textarea class="form-control" name="address" id="address"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Latitude</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="latitude" id="latitude" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Longitude</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="longitude" id="longitude" />
</div>
</div>
</fieldset>
<div class="form-group">
<div class="col-lg-9 col-lg-offset-3">
<button type="submit" class="btn btn-primary" onclick="companyFormValidation()" >Submit</button>
</div>
</div>
</form>
Here is the code with return false if any field is empty.
<script>
function companyFormValidation()
{
var name = document.getElementById('companyname').value;
var title = document.getElementById('companytitle').value;
var desc = document.getElementById('description').value;
var logo = document.getElementById('logo').value;
var email = document.getElementById('emailid').value;
var website = document.getElementById('siteurl').value;
var phonenumber = document.getElementById('phonenumber').value;
var faxNumber = document.getElementById('faxNumber').value;
var address = document.getElementById('address').value;
var latitude = document.getElementById('latitude').value;
var longitude = document.getElementById('longitude').value;
if(name == '')
{
alert('Name can not empty');
//$("#ename").html("Name can't be empty..");
return false;
}
}
</script>
<form id="addCompanyForm" method="post" action="#" onsubmit="return companyFormValidation()" class="form-horizontal" >
<fieldset>
<legend>Company </legend>
<div class="form-group">
<label class="col-lg-3 control-label">Name</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="companyname" id='companyname' />
<div id="ename"></div>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Title</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="companytitle" id="companytitle" />
<div id="etitle"></div>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Description</label>
<div class="col-lg-5">
<textarea class="form-control" name="description" id = "description"></textarea>
<div id="edesc"></div>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Logo</label>
<div class="col-lg-5">
<input type="file" class="form-control" name='logo' id="logo" >
<!-- <span class="input-group-btn">
<span class="btn btn-default btn-file">
Browse… <input type="file" name="">
</span>
</span> -->
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email </label>
<div class="col-lg-5">
<input type="text" class="form-control" name="emailid" id="emailid"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Website</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="siteurl" placeholder="http://" id="siteurl" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Phone number</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="phonenumber" id="phonenumber"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Fax number</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="faxNumber" id="faxNumber" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Address</label>
<div class="col-lg-5">
<textarea class="form-control" name="address" id="address"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Latitude</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="latitude" id="latitude" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Longitude</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="longitude" id="longitude" />
</div>
</div>
</fieldset>
<div class="form-group">
<div class="col-lg-9 col-lg-offset-3">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</div>
</form>
Your code is written in js and you are asking for jquery. For jquery use above answer.
You may use validate JS "jquery.validate.min.js" for jquery validation. It's a simple. You want the demo you can check it http://www.sitepoint.com/basic-jquery-form-validation-tutorial/. Hope this helps to you, Thanks!

Categories