onkeyup (function) not registering - javascript

I am trying to validate a form. I'm doing this by creating a JS code that ensures all text fields have atleast a character in it and if not the submit button is disabled. However, when i run this code my submit button becomes active after filling out only one field.
Also if you find any bugs etc please point them out, cheers.
This is my HTML
<form name = "form" onsubmit="validate()">
<h3>Please complete the form below. Mandatory fields marked with *</h3>
<fieldset>
<h4>Personal Details</h4>
<p>
<label for="fname">*First Name</label> <input type="text" name="fname" id="fname" placeholder="First Name" onKeyup="validate()" class = "form" >
</p>
<p>
<label for="lname">*Last Name</label> <input type="text" name="lname" id="lname" placeholder="Last Name" onKeyup="validate()" class = "form" />
</p>
<p>
<label for="Etype">Gender</label>
<select class = "form" id="gender" name="gender"><option value="">Select...</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</p>
<p>
<label for="age">*Age</label>
<select class = "form" id="age" name="age"><option value="">Select...</option>
<option value="youngest">3-7</option>
<option value="young">7-12</option>
<option value="teen">12-16</option>
<option value="young-adult">16-18</option>
<option value="adult">18+</option>
</select>
</p>
<p>
<label for="s_add">*Street Address</label> <input type="text" name="s_add" id="s_add" placeholder="Insert Street Address" onKeyup="validate()" class = "form" />
</p>
<p>
<label for="s_sub">*Suburb</label> <input type="text" name="s_sub" id="s_sub" placeholder="Suburb" onKeyup="validate()" class = "form"/>
</p>
<p>
<label for="state">*State</label> <input type="text" name="state" id="state" onKeyup="validate()" class = "form" />
</p>
<p>
<label for="pcode">*Postcode</label> <input type="text" name="pcode" id="pcode" onKeyup="validate()" class = "form" />
</p>
<p>
<label for="phone">*Phone</label> <input type="text" name="phone" id="phone" placeholder="Mobile or Home" onKeyup="validate()" class = "form"/>
</p>
<p>
<label for="email">*Email</label> <input type="text" name="email" id="email" placeholder="Email Address" onKeyup="validate()" class = "form"/>
</p>
</fieldset>
<fieldset>
<h4>Emergency Contact</h4>
<p> please select someone within a close vicinity of 'Clowning Around'. </p>
<p>
<label for="fname">*First Name</label> <input type="text" name="fname" id="fname" onKeyup="validate()" placeholder="First Name" class = "form" />
</p>
<br>
<p>
<label for="lname">*Last Name</label> <input type="text" name="lname" id="lname" placeholder="Last Name" onKeyup="validate()" class = "form" />
</p>
<br>
<p>
<label for="s_add"> *Street Address</label> <input type="text" name="s_add" id="s_add" placeholder="Insert Street Address" onKeyup="validate()" class = "form" />
</p>
<br>
<p>
<label for="Mnum"> *Mobile Number</label> <input type="text" name="Mnum" id="Mnum" placeholder="Mobile Number" class = "form" />
</p>
<br>
<p>
<label for="Relationship"> *Relationship</label> <input placeholder="E.g Parent" class = "form"/>
</p>
<br>
<p>
<input id="SubmitButton" type="submit" disabled="disabled" value="Submit" />
</fieldset>
<fieldset>
<h4> Type of Enrollment </h4>
<label for="Etype">*What would you like to enrol in?</label>
<select class = "form" id="Etype" name="Etype"><option value="">Select...</option>
<option value="Camp">Camp</option>
<option value="Class">Class</option>
</select>
</p>
</form>
</body>
</fieldset>
as you can see in my code ive added onKeyup="validate()" in the inputs.
This is my JS
window.onload = function() {
console.log("The window has finished loading");
var SubmitButton = document.getElementById("SubmitButton");
SubmitButton.addEventListener('click', function() {
console.log("The submit button has been clicked");}, false);
var fname = document.getElementById("fname");
fname.addEventListener('keyup', function() {
console.log((fname).value);}, false);
var lname = document.getElementById("lname");
lname.addEventListener('keyup', function() {
console.log((lname).value);
validate();}, false);
}
function validate()
{
var x = document.forms["form"].elements;
var xbutton = true;
for (var i = 0; i < xbutton.length; i++) {
if (x[i].value.length == 0) xbutton = false;
}
if (xbutton) {
document.getElementById('SubmitButton').disabled = !xbutton;
}
}
I've added the first function just in case its related.
Edit:
I've fixed var i = 0; i < xbutton.length; i++
to x.length
Now when i run the code i get an Uncaught TypeError: Cannot read property 'length' of undefined
for line if (x[i].value.length == 0) xbutton = false;
any ideas?

The for loop isn't right, you refer to xbutton.length but it should be x.length because x is the list of elements and xbutton is a boolean:
for (var i = 0; i < x.length; i++) {
Also, you're duplicating the event handlers by using both the inline onkeyup and addEventListener. Use one or the other.
Finally, in the onsubmit handler, you need to return false in order to prevent the form from submitting, if the validation fails.
The new error occurs because you have fieldset elements included in the form.elements list, so you're trying to get the value of a fieldset which doesn't exist. To resolve that, add a condition to check that the element is an input[type=text]:
for (var i = 0; i < x.length; i++) {
if(x[i].tagName == 'INPUT' && x[i].type == 'text'){
if (x[i].value.length == 0) xbutton = false;
}
}

Related

Why does my submit button not work properly?

I have a form created using HTML and I have a submit button.
I am trying to have the submit button disabled if the fields are not filled out.
However, now even if the fields are filled out the button stays disabled.
const subButton = document.querySelector('.sbutton')
const inputTexts = document.querySelector('.input')
subButton.disabled = true
function clickedButton() {
if (document.querySelector('.input').value === "") {
subButton.disabled = true
} else {
subButton.disabled = false
}
}
<div class="form">
<section>
<form action=[link] method="POST">
<fieldset>
<legend>Your Contact Info!</legend>
<label class="firstname" for="firstname">First Name</label>
<input class="input" type="text" id="firstname" name="name" placeholder="Your first name" required>
<label class="lastname" for="lastname">Last Name</label>
<input type="text" id="lastname" name="lname" placeholder="Your last name">
<label class="email" for="email">E-mail</label>
<input class="input" type="email" id="email" name="email" placeholder="Your e-mail" required>
<label class="comments" for="comments">Additional Comments</label>
<textarea class="input" placeholder="Anything else we should know!" id="comments" name="comments" required></textarea>
<label class='input' for="timeofday">When is the best time of day to contact you?</label>
<select id="timeofday" name="timeofday">
<option value='Morning'>Morning</option>
<option selected value="afternoon">Afternoon</option>
<option value="evening">Evening</option>
</select>
</fieldset>
<button class="sbutton" type="submit">Submit</button>
The issue is, that you never call the function clickedButton(). You need an eventListener that listens for change events within the inputs and then calls that function:
const INPUTS = document.querySelectorAll('input');
INPUTS.forEach(el =>
el.addEventListener('change', clickedButton)
)
const subButton = document.querySelector('.sbutton')
const inputTexts = document.querySelector('.input')
const INPUTS = document.querySelectorAll('input');
subButton.disabled = true
INPUTS.forEach(el =>
el.addEventListener('change', clickedButton)
)
function clickedButton() {
if (document.querySelector('.input').value === "") {
subButton.disabled = true
} else {
subButton.disabled = false
}
}
<div class="form">
<section>
<form action=[link] method="POST">
<fieldset>
<legend>Your Contact Info!</legend>
<label class="firstname" for="firstname">First Name</label>
<input class="input" type="text" id="firstname" name="name" placeholder="Your first name" required>
<label class="lastname" for="lastname">Last Name</label>
<input type="text" id="lastname" name="lname" placeholder="Your last name">
<label class="email" for="email">E-mail</label>
<input class="input" type="email" id="email" name="email" placeholder="Your e-mail" required>
<label class="comments" for="comments">Additional Comments</label>
<textarea class="input" placeholder="Anything else we should know!" id="comments" name="comments" required></textarea>
<label class='input' for="timeofday">When is the best time of day to contact you?</label>
<select id="timeofday" name="timeofday">
<option value='Morning'>Morning</option>
<option selected value="afternoon">Afternoon</option>
<option value="evening">Evening</option>
</select>
</fieldset>
<button class="sbutton" type="submit">Submit</button>
Note, that you check only the first input. querySelector returns only 1 element (the first).
Nothing on the page is calling clickedButton()
Attach an EventListener for changes on the form that calls this function.
var form = document.querySelector('form');
form.addEventListener('change', clickedButton);
Also when you are using querySelector you will only get the first element in the form which is a <input .... If you want to check for all you should use querySelectorAll.
But that function would return an array so then you need to check if all of them have text.
In that case you could do it like this.
function validateForm() {
// Get all elements
const elements = document.querySelectorAll("input");
// Filter out elements that have no value, if there is more then 1 set disabled to true, else it is false
const disabled = elements.filter((el) => el.value === "").length > 0 ? true : false;
subButton.disabled = disabled
}
And if you are going with this way you need to call this function instead of the other one like this:
var form = document.querySelector('form');
form.addEventListener('change', validateForm);

Is there a way to get your JQuery validation to populate onto the document?

For one of my classes we're using JQuery validation. I'm trying to get the answers to populate next to the corresponding text on the bottom that's listed (name, age, date,etc..) on the document below after the user inputs the info in the text box.
<script>
$(document).ready(function() {
$("#input").validate();
$("#input").submit(function(e) {
e.preventDefault(); //Prevents from submitting (which is the default action)
if (!$("#input").valid()) {
return false;
} else {
$("#result").append($("#name").val() + "<br>" + "Your name is");
}
});
});
</script>
<body>
<p><b>Fill out all the fields below and click submit</b></p>
<div>
<label for="name" class="label">Enter your name</label>
<input type="text" name="name" id="name" class="required" title="Please enter your name"> </div><br>
<div>
<label for="thedate" class="label">Enter today's date</label>
<input type="text" name="thedate" id="thedate" class="required date"></div><br>
<div>
<label for="theage" class="label">Enter your age</label>
<input type="text" name="theage" id="theage" class="required digits"></div><br>
<div>
<label for="theurl" class="label">Enter your web site</label>
<input type="text" name="theurl" id="theurl" class="required url"></div><br>
<div>
<label for="theemail" class="label">Enter your email</label>
<input type="text" name="theemail" id="theemail" class="required email"></div><br>
<div>
<input type='submit' value='Submit' name="submit" id='submitme'></div><br>
</form>
<p id="result"></p>
<p><b>Name:</b></p><br>
<p><b>Date: </b></p><br>
<p><b>Age:</b> </p><br>
<p><b>Website: </b></p><br>
<p><b>Email:</b></p><br>
</body>
</html>

Checkbox not display element when checked in meteor

I am working in meteor and am trying to display a block of code when a checkbox is checked. I am new to JS and jquery, but I have research different ways of writing the JS. This is what I came up with:
<div class="recipient">
<div class="toRecipient-container">
<label class="toRecipient">TO:</label>
<input class="toRecipient" type="text" size="45">
</div>
<br>
<div id="checkbox-container" class="checkbox-container">
<label for="newClient">New Client
<input id="newClient" class="newInfo" type="checkbox" onclick="toggle()"></label>
<label for="newBilling" style="padding-left: 20px;">New Billing
<input id="newBilling" class="newInfo" type="checkbox"></label>
</div>
</div>
<div id="billingDetails-container" class="billingDetails-container">
<div class="billingDetails">
<label>Billing Contact:</label>
<input class="billingContact" type="text" size="45">
<label>Billing Phone:</label>
<input class="billingPhone" type="text" size="45">
<div>
<label>Billing Address:</label>
<input class="billingAddress" type="text" placeholder="Street Address" size="45">
<input class="billingAddress" type="text" placeholder="City" size="45">
<input class="billingAddress" type="text" placeholder="State" size="45">
<input class="billingAddress" type="text" placeholder="Zip Code" size="45">
</div>
<label>Billing Email:</label>
<input class="billingEmail" type="text" size="45">
</div>
</div>
And my JS:
Template.InvoicePage.onCreated(function () {
this.state = new ReactiveVar();
});
Template.InvoicePage.helpers({
toggle: ()=>{
var checkBox = document.getElementById("newClient");
var displayBlock = document.getElementById("billingDetails-container");
if (checkBox.checked == true) {
displayBlock.style.display = "block";
} else {
displayBlock.style.display = "none";
}
},
});
Template.InvoicePage.events({
'change #newClient'(event, instance) {
instance.state.set('newClient', event.target.checked)
},
});
When I check the box, I get an error that 'toggle' is undefined. Should this be a template event instead of a helper? What am I missing?
I've never done anything with meteor. There is a lot of different frameworks listed on the website. I'm not sure which one you use (if any). You can't possibly use angular, react and vuejs all at the same time.
Unless I'm wrong and there is a particular reason for the whole
Template.InvoicePage.helpers({...});
simply do
function toggle() {
var checkBox = document.getElementById("newClient");
var displayBlock = document.getElementById("billingDetails-container");
if (checkBox.checked == true) {
displayBlock.style.display = "block";
} else {
displayBlock.style.display = "none";
}
}
It has nothing to do with a framework. Just vanilla javascript and html.
I believe you are trying to show the billingDetails-container when the user selects the New-Client check-box. If that is correct, the below should work
HTML
<div class="recipient">
<div class="toRecipient-container">
<label class="toRecipient">TO:</label>
<input class="toRecipient" type="text" size="45">
</div>
<br>
<div id="checkbox-container" class="checkbox-container">
<label for="newClient">New Client
<input id="newClient" class="newInfo" type="checkbox"></label>
<label for="newBilling" style="padding-left: 20px;">New Billing
<input id="newBilling" class="newInfo" type="checkbox"></label>
</div>
</div>
{{#if showBillingDetails}}
<div id="billingDetails-container" class="billingDetails-container">
<div class="billingDetails">
<label>Billing Contact:</label>
<input class="billingContact" type="text" size="45">
<label>Billing Phone:</label>
<input class="billingPhone" type="text" size="45">
<div>
<label>Billing Address:</label>
<input class="billingAddress" type="text" placeholder="Street Address" size="45">
<input class="billingAddress" type="text" placeholder="City" size="45">
<input class="billingAddress" type="text" placeholder="State" size="45">
<input class="billingAddress" type="text" placeholder="Zip Code" size="45">
</div>
<label>Billing Email:</label>
<input class="billingEmail" type="text" size="45">
</div>
</div>
{{/if}}
JS
Template.InvoicePage.events({
'change #newClient'(event, instance) {
instance.state.set({
'newClient': event.target.checked //Here, we are set the newclient property of state object based on client's selection.
});
}
});
Template.InvoicePage.helpers({
showBillingDetails() {
const state = Template.instance().state.get();
return state && state.newClient; //Here, we use the newclient property of state to decide whether or not to display the billingDetails-container
}
});

Javascript form validation not working with one field but works with the others

I for some reason can not get the rep id field to validate with my script. I've spent hours on it and can't figure it out. All other fields validate just fine except the repid.
Here is the code I am using for the form
<form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="repsignup" id="repsignup">
<h1>Janoo Rep Sign Up</h1>
<p>Join our growing team and help rep Janoo out there in the world!</p>
<p> </p>
<h4>
Name (First and Last):
<input name="name" type="text" required="required" id="name" form="repsignup" placeholder="John Doe" size="70" maxlength="70" />
</h4>
<h4>
<label for="repid">Rep ID:</label>
<input name="repid" type="text" id="repid" form="repsignup" placeholder="DoeJ" size="32" maxlength="15" />
</h4>
<h4>
<label for="email">Email:</label>
<input name="email" type="email" required="required" id="email" form="repsignup" placeholder="Jdoe#gmail.com" size="89" maxlength="100" />
</h4>
<p><strong>* Your default password is "password" all lowercase! Please change it as soon as you log in.</strong></p>
<p> </p>
<p>*As of right now we only have reps in the United States</p>
<h4>
<label for="address">Address:</label>
<input name="address" type="text" required="required" id="address" form="repsignup" placeholder="12345 Street" size="86" />
</h4>
<h4>
<label for="city">City:</label>
<input name="city" type="text" required="required" id="city" form="repsignup" placeholder="Detroit" size="92" />
</h4>
<h4>
<label for="country">State:</label>
<input name="State" type="text" required="required" id="address3" form="repsignup" placeholder="ex. MI" size="90" maxlength="2" />
</h4>
<h4>
<label for="address5">Zipcode:</label>
<input name="zipcode" type="text" required="required" id="address5" form="repsignup" placeholder="48201" size="87" />
</h4>
<h4>
<label for="gender">Gender:</label>
<select name="gender" size="1" id="gender" form="repsignup">
<option value="Null">No Answer</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</h4>
<h4>
<label for="birthday">Birthday:</label>
<input name="birthday" type="date" required="required" id="birthday" form="repsignup" />
</h4>
<h4>
<label for="about">About you:<br />
</label>
<textarea name="about" cols="100" rows="10" maxlength="250" id="about" form="repsignup"></textarea>
</h4>
<h4>
<label for="shirtsize">Shirt Size:</label>
<select name="shirtsize" id="shirtsize" form="repsignup">
<option value="as">Adult Small</option>
<option value="am">Adult Medium</option>
<option value="al">Adult Large</option>
<option value="axl">Adult XL</option>
<option value="axxl">Adult XXL</option>
</select>
</h4>
<h4>What team are you appling for? (Select all that apply) </h4>
<p>
<input name="skate" type="checkbox" id="skate" form="repsignup" />
<label for="skate">Skateboard </label>
</p>
<p>
<input name="snow" type="checkbox" id="snow" form="repsignup" />
<label for="snow">Snowboard </label>
</p>
<p>
<input name="longboard" type="checkbox" id="longboard" form="repsignup" />
Longboard
</p>
<p>
<input name="video" type="checkbox" id="video" form="repsignup" />
Video Production
</p>
<p>
<input name="music" type="checkbox" id="music" form="repsignup" />
Music Production
</p>
<p>
<input name="model" type="checkbox" id="model" form="repsignup" />
<label for="model">Modeling </label>
</p>
<p> </p>
<h4>Links to your contacts</h4>
<p>
<label for="instagram">Instagram:</label>
<input name="instagram" type="text" id="instagram" form="repsignup" size="86" maxlength="80" />
</p>
<p>
<label for="facebook">Facebook:</label>
<input name="facebook" type="text" id="facebook" form="repsignup" size="86" maxlength="80" />
</p>
<p>
<label for="twitter">Twitter:</label>
<input name="twitter" type="text" id="twitter" form="repsignup" size="86" maxlength="80" />
</p>
<p>
<label for="youtube">YouTube:</label>
<input name="youtube" type="text" id="youtube" form="repsignup" size="86" maxlength="80" />
</p>
<p>
<label for="website">Website:</label>
<input name="website" type="text" id="website" form="repsignup" size="86" maxlength="80" />
</p>
<p>
<label for="otherlinks">Other:</label>
<input name="otherlinks" type="text" id="otherlinks" form="repsignup" size="86" maxlength="80" />
</p>
<p> </p>
<p><strong>Here is some stuff you should read up on:</strong></p>
<p>Reps are paid out when they hit $5 in commison.</p>
<p>Rep codes do NOT work with coupons.</p>
<p>Default commison is 10% of all your sales but may vary.</p>
<p> </p>
<p><strong>For any of your media content to be used you must agree to the the terms and conditions</strong></p>
<p>
<input name="media" type="checkbox" disabled="disabled" id="media" form="repsignup" checked="checked" />
I agree to the terms and conditions for usage of my media and allow the promotion of me as a individual </p>
<p>
<input name="inform" type="checkbox" id="inform" form="repsignup" checked="checked" />
<label for="inform">Inform me of my sales</label>
as a rep
</p>
<p>
<input name="DATE" type="hidden" id="DATE" value="<?php echo date('Y-m-d'); ?>" />
<input name="com" type="hidden" id="com" form="repsignup" value="10" />
<input name="country" type="hidden" id="country" value="United States of America" />
<input name="password" type="hidden" id="password" form="repsignup" value="861aab8d5bdd93565a7454e5e5754f8f" />
<input name="1" type="hidden" id="1" value="1" />
<input name="discount" type="hidden" id="discount" value="5" />
<input name="2" type="hidden" id="2" value="2" />
<input name="enddate" type="hidden" id="enddate" value="3000-01-01 00:00:00" />
<input name="avail" type="hidden" id="avail" value="30000000" />
</p>
<p>
<?php print imageorsubmit(#$imgsubmit,$GLOBALS['xxSubmt'],'submit')?></p>
<p>
<input type="hidden" name="MM_insert" value="repsignup" />
</p>
</form>
And here is the javascript I am using to validate it
<script type="text/javascript">
$( document ).ready(function() {
$("#repsignup").submit(function(event){
//alert("The paragraph was clicked.");
var name = $("#name").val();
var repid = $("#repid").val();
var address = $("#address").val();
var city = $("#city").val();
var state = $("#address3").val();
var zipcode = $("#address5").val();
var gender = $("#gender").val();
var birthday = $("#birthday").val();
var about = $("#about").val();
var skate = $("#skate").val();
var snow = $("#snow").val();
var longboard = $("#longboard").val();
var video = $("#video").val();
var music = $("#music").val();
/*Social fields*/
var instagram = $("#instagram").val();
var facebook = $("#facebook").val();
var twitter = $("#twitter").val();
var youtube = $("#youtube").val();
var website = $("#website").val();
var otherlinks = $("#otherlinks").val();
//alert(name.split(" ").length);
var a = isValidCharacter(name);
//alert(a);
/*Name validation*/
if(name.split(" ").length==2 && a)
;
else{
alert('Please enter first and last name separated by a space. No special character is allowed');
event.preventDefault();
}
validRepid = isValidCharacter(repid);
if(repid.indexOf('>') > -1 || repid.indexOf('<') > -1){
alert('Rep ID should not have any special character.');
event.preventDefault();
}
validAddress = isValidCharacter(address);
if(address.indexOf('>') > -1 || address.indexOf('<') > -1){
alert('Address should not have any special character.');
event.preventDefault();
}
validCity = isValidCharacter(city);
if(city.indexOf('>') > -1 || city.indexOf('<') > -1){
alert('City should not have any special character.');
event.preventDefault();
}
validState = isValidCharacter(state);
if(state.indexOf('>') > -1 || state.indexOf('<') > -1){
alert('State should not have any special character.');
event.preventDefault();
}
validZipcode = isValidCharacter(zipcode);
if(zipcode.indexOf('>') > -1 || zipcode.indexOf('<') > -1){
alert('Zipcode should not have any special character.');
event.preventDefault();
}
validGender = isValidCharacter(gender);
if(gender.indexOf('>') > -1 || gender.indexOf('<') > -1){
alert('Gender should not have any special character.');
event.preventDefault();
}
if (birthday.indexOf('>') > -1 || birthday.indexOf('<') > -1)
{
alert('Birthday should not have any special character.');
event.preventDefault();
}
validAbout = isValidCharacter(about);
if(!validAbout){
alert('About field should not have any special character.');
event.preventDefault();
}
var flag = false;
if($("#skate").prop("checked"))
flag = true;
if($("#snow").prop("checked"))
flag = true;
if($("#skate").prop("checked"))
flag = true;
if($("#longboard").prop("checked"))
flag = true;
if($("#video").prop("checked"))
flag = true;
if($("#music").prop("checked"))
flag = true;
if($("#model").prop("checked"))
flag = true;
if(flag==false){
alert('Please select at least one team to apply for.');
event.preventDefault();
}
if(instagram.indexOf('>') > -1 || instagram.indexOf('<') > -1){
alert('Instagram field should not have any special character.');
event.preventDefault();
}
if(facebook.indexOf('>') > -1 || facebook.indexOf('<') > -1){
alert('Facebook field should not have any special character.');
event.preventDefault();
}
if(twitter.indexOf('>') > -1 || twitter.indexOf('<') > -1){
alert('Twitter field should not have any special character.');
event.preventDefault();
}
if(youtube.indexOf('>') > -1 || youtube.indexOf('<') > -1){
alert('Youtube field should not have any special character.');
event.preventDefault();
}
if(website.indexOf('>') > -1 || website.indexOf('<') > -1){
alert('Website field should not have any special character.');
event.preventDefault();
}
if(otherlinks.indexOf('>') > -1 || otherlinks.indexOf('<') > -1){
alert('Otherlinks field should not have any special character.');
event.preventDefault();
}
});
});
function isValidCharacter(str){
return !/[~`#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
</script>
you can validate all fields without getting each single value and only using one function for it:
$(document).ready(function(){
var allFine = true;
function valdiate(){
var value = $(this).val();
if(value !== null && value.trim().length() > 0 && !value.match(/[\<\>]/));
var allFine = false;
$(this).css('border', '1px solid red');
}
// selector for all required input and textarea tags in your html
$('form').find('input:required, textarea:required').each(validate);
$('form').on('submit', function(){
if(!allFine) {
event.preventDefault();
event.stopPropagination();
alert('there is a failure, have a look on the red bordered fields');
}
// otherwise the form is submitted normal
});
})
if you need to check all input fields for validation, remove the :required flag in the selector and remove null and length check from the if
remember, if you use html5 you also can use pattern attribute to input element with regex:
<input name="myInput" type="text" pattern="[a-zA-Z0-9 .,-]" required>
or some other regex you want

Display and hide fields of a form after select

I have a javascript function that display and hide a div after select.
The div contains fields of a form. The div test2 has the fields of the div test1 plus other fields. All the fields are required.
I have 2 problems:
1) When I display test2 and I complete the fields, saving the form is impossible because some fields in test2 are found in test1. This means some fields have the same name.
2) All the fields are required, which means even if I complete the fields in test2 I still can't save because the fields in test1 are not completed and hidden. How can I create a code structure to allow this to save?
function visibilite1(_this) {
var id = _this.value;
var divs = document.getElementsByTagName('div');
for(var no=0;no<divs.length;no++) {
if (divs[ no].className=='divs') {
'divs'
divs[ no].style.display = "none";
}
}
document.getElementById(id).style.display = "block";
}
<select name="role" id="role"
onchange="visibilite1(this);hide()" >
<option value='test1'>Year1</option>
<option value='test2'>Year2</option>
</select>
<div id="test1" class="divs">
<label>Name </label>
<input type="text" name= "name" id= "name" required> </br>
<label>User name </label>
<input type="text" name= "username" id= "username" required></br>
<label >Password <em>*</em></label>
<input type="password" name= "password" id= "password" required></br>
</div>
<div id="test2" class="divs">
<label>Name </label>
<input type="text" name= "name" id= "name" required>
<label>User name </label>
<input type="text" name= "username" id= "username" required>
<label>Password <em>*</em></label>
<input type="password" name= "password" id= "password" required>
<input type="text" name= "username" id= "username" required>
<label>Adress<em>*</em></label>
<input type="text" name= "adress" id= "adress" required>
<label>Client name</label>
<?php
$sql="select ClientName from claims_follow_up.Client where id
!='10001' order by ClientName asc ";
$req=mysqli_query($dbc,$sql) or die("Erreur d'execution");
?>
<select name="ClientName" id="ClientName"
onchange="
var maVal = document.getElementById('ClientName').value;
if (maVal == 'Create new client')
{
window.open('newClientCreate.php', 'blank', 'scrollbars=yes,
resizable=no, top=50, left=155, width=1200, height=700');
};activer()" required disabled="true" onkeypress="activerSubmit()">
<option value="">select client </option>
<?php
while($d=mysqli_fetch_array($req))
{
echo'<option
value="'.$d['ClientName'].'">'.$d['ClientName'].'</option>';
}
mysqli_free_result($req);
?>
<option value="Create new client" style="color:blue;
font-weight:bold">create new client</option>
</select>
</div>
As you've discovered, elements in a html page should never have the same id and different input elements in a html form should not have the same name.
Assuming you want to stay within the world of vanilla javascript and don't want to use a javascript framework (e.g. angular, ember) you could accomplish this by setting the inner html of elements. This way the "hidden" html isn't present in the html markup.
Something like...
<script>
function hide () {
console.log("whatever")
}
function visibilite1(_this) {
var formgroup1 = '<div id="test1" class="divs"><label>Name </label><input type="text" name= "name" id= "name" required> </br><label>User name </label><input type="text" name= "username" id= "username" required></br><label >Password <em>*</em></label><input type="password" name= "password" id= "password" required></br></div>'
var formgroup2 = '<div id="test2" class="divs"><label>Name </label><input type="text" name= "name" id= "name" required><label>User name </label><input type="text" name= "username" id= "username" required><label>Password <em>*</em></label><input type="password" name= "password" id= "password" required><input type="text" name= "username" id= "username" required><label>Adress<em>*</em></label><input type="text" name= "adress" id= "adress" required></div>'
var formtestElement = document.getElementById('formtest');
if (_this.value == "test1") {
formtestElement.innerHTML = formgroup1
} else if (_this.value == "test2") {
formtestElement.innerHTML = formgroup2
};
}
</script>
<select name="role" id="role"
onchange="visibilite1(this);hide()" >
<option value='test1'>Year1</option>
<option value='test2'>Year2</option>
</select>
<div id="formtest">
<div id="test1" class="divs">
<label>Name </label>
<input type="text" name="name" id="name" required> </br>
<label>User name </label>
<input type="text" name="username" id="username" required></br>
<label>Password <em>*</em></label>
<input type="password" name="password" id="password" required></br>
</div>
</div>
Update: Edited to show the test1 form by default.
Another approach is to clone elements and on show/hide putting the right one in the form.In the window onload event I set the select to the desired index and I clone and save the elements, removing from the form the elements hidden. on change I remove the visible element and add the selected one.
var divsCloned = [];
function visibilite1(_this) {
if (divsCloned.length == 0) {
return;
}
var currDiv = document.getElementsByTagName('div')[0];
_this.parentNode.removeChild(currDiv);
_this.parentNode.insertBefore(divsCloned[_this.selectedIndex], _this.nextSibling);
}
window.onload = function() {
var divs = document.getElementsByTagName('div');
for (var no = 0; no < divs.length; no++) {
divsCloned.push(divs[no].cloneNode(true));
if (no != 0 && divs[no].parentNode) {
divs[no].parentNode.removeChild(divs[no]);
}
}
}
<form>
<select name="role" id="role"
onchange="visibilite1(this);">
<option value='test1'>Year1</option>
<option value='test2'>Year2</option>
</select>
<div id="test1" class="divs">
<label>Name </label>
<input type="text" name="name" id="name" required> </br>
<label>User name </label>
<input type="text" name="username" id="username" required></br>
<label>Password <em>*</em></label>
<input type="password" name="password" id="password" required></br>
</div>
<div id="test2" class="divs">
<label>Name </label>
<input type="text" name="name" id="name" required>
<label>User name </label>
<input type="text" name="username" id="username" required>
<label>Password <em>*</em></label>
<input type="password" name="password" id="password" required>
<input type="text" name="username" id="username" required>
<label>Adress<em>*</em></label>
<input type="text" name="adress" id="adress" required>
</div>
<input id="submit" type="submit" value="Submit">
</form>
1st thing don't put same id for 2 components, even if its in different divs...
2nd to achieve ur result, when ever u hide the div, disable the input fields corresponding to it and re-enble it when u need
Immediate reaction is that IDs in the document must be unique! - form element names can be the same, but that implies that they are part of a group (ie: within option buttons collection where there's only one possible selection).
Best to keep them all unique, else you need to refer specifically to formName plus elementName.
Whenever you hide a div, set all of the inputs inside of it as disabled. When an input is disabled, the required attribute is ignored, and disabled inputs don't get submitted with the form, so you won't have the name collisions on the back-end.
var inputs = divs[no].getElementsByTagName('input');
for (var x = 0, len = inputs.length; x < len; x++) {
inputs[x].disabled = true;
}
Obviously, when you unhide a div, you'll need to go through and re-enable all of the inputs within that div, as well.
Update: Here's an example using your given code, as requested. First, the JS:
function visibilite1(_this) {
var inputs;
var divToShow;
var id = _this.value;
var divs = document.getElementsByTagName('div');
for(var no=0;no<divs.length;no++) {
if (divs[no].className=='divs') {
divs[no].style.display = "none";
inputs = divs[no].getElementByTagName('input');
for (var x = 0, len = inputs.lenght; x < len; x++) {
inputs[x].disabled = true;
}
}
}
divToShow = document.getElementById(id);
divToShow.style.display = "block";
inputs = divToShow.getElementByTagName('input');
for (var x = 0, len = inputs.lenght; x < len; x++) {
inputs[x].disabled = false;
}
}
And the HTML (reduced a little, but enough to see what it should look like):
<select name="role" id="role" onchange="visibilite1(this);hide()" >
<option value='test1'>Year1</option>
<option value='test2'>Year2</option>
</select>
<div id="test1" class="divs">
<label>Name </label>
<input type="text" name= "name" required> </br>
<label>User name </label>
<input type="text" name= "username" required></br>
<label >Password <em>*</em></label>
<input type="password" name= "password" required></br>
</div>
<div id="test2" class="divs">
<label>Name </label>
<input type="text" name= "name" required>
<label>User name </label>
<input type="text" name= "username" required>
<label>Password <em>*</em></label>
<input type="password" name= "password" required>
<input type="text" name= "username" required>
<label>Adress<em>*</em></label>
<input type="text" name= "adress" required>
</div>

Categories

Resources