I'm trying to do my first form validation with only Vanilla JS.
I have a form, that has two selects in which you have to select your department and depending on this it will allow you to select another location. I made a script for this.
Now, when I relate another script which is formValidation, it doesn't work and I guess I'm doing the form validation well. I'm starting doing it so it only has one validation but it isn't working.
What could be the problem? When i wrote the form validation in the script file, it override the function or the selects so it didn't work. I don't know how to else doing a form validation because I'm new to JS and I'm not allowed to use jquery or anything.
Thanks
Here is the code pen:
https://codepen.io/yomiram/pen/abNMaMy
HTML :
<section id="formSection">
<span class="textForm">Formulario</span>
<hr>
<form action="/" id="form" action="GET">
<div class="form-group">
<input type="text" placeholder="Nombre" id="name" class="input-control" required/>
<input type="text" placeholder="Apellido" id="lastName" class="input-control" />
</div>
<div class="form-group">
<input type="email" placeholder="E-mail" id="email" class="input-control" required/>
</div>
<div class="form-group">
<select class="input-control" style="flex: 6" id="dpto" required>
<option selected="selected" class="department">Departamento</option>
</select>
<select class="input-control" placeholder="Localidad" id="location" style="flex:6" required>
<option selected="selected" class="department">Localidad</option>
</select>
</div>
<div class="form-group">
<input type="number" id="ci" class="input-control" placeholder="C.I" style="flex:6" required/>
</div>
<div class="form-group">
<input type="checkbox" name="conditions" id="conditions" required>
<label for="conditions" id="conditions"> Acepto las bases y condiciones</label><br>
</div>
<div class="form-group">
<input type="submit" id="formButton" class="formButton" value="Enviar">
</div>
</form>
</section>
SCRIPT JS (SELECT FUNCTION):
// DISPLAYING DATA IN SELECT
var dptosLocs = {
"Artigas":["Artigas"," Bella Unión"],
"Canelones":["Canelones"," Santa Lucía"],
"Montevideo":["Montevideo"],
"Salto":["Salto"," Daymán"," Arapey"]
};
var sel = document.getElementById('dpto');
var fragment = document.createDocumentFragment();
Object.keys(dptosLocs).forEach(function(dptosLoc, index) {
var opt = document.createElement('option');
opt.innerHTML = dptosLoc;
opt.value = dptosLoc;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
document.getElementById("dpto").onchange = function() {defineDpto()};
function defineDpto() {
var dpto = document.getElementById("dpto").value;
if (dpto == "Artigas" ) {
var sel = document.getElementById('location');
var fragment = document.createDocumentFragment();
Object.values(dptosLocs["Artigas"]).forEach(function(dptosLoc, index) {
var opt = document.createElement('option');
opt.innerHTML = dptosLoc;
opt.value = dptosLoc;
fragment.appendChild(opt)
sel.appendChild(fragment);
});
} else if (dpto == "Canelones") {
document.getElementById('location').options.length = 0;
var sel = document.getElementById('location');
var fragment = document.createDocumentFragment();
Object.values(dptosLocs["Canelones"]).forEach(function(dptosLoc, index) {
var opt = document.createElement('option');
opt.innerHTML = dptosLoc;
opt.value = dptosLoc;
fragment.appendChild(opt)
sel.appendChild(fragment);
});
} else if (dpto == "Montevideo") {
document.getElementById('location').options.length = 0;
var sel = document.getElementById('location');
var fragment = document.createDocumentFragment();
Object.values(dptosLocs["Montevideo"]).forEach(function(dptosLoc, index) {
var opt = document.createElement('option');
opt.innerHTML = dptosLoc;
opt.value = dptosLoc;
fragment.appendChild(opt)
sel.appendChild(fragment);
});
} else if (dpto == "Salto") {
document.getElementById('location').options.length = 0;
var sel = document.getElementById('location');
var fragment = document.createDocumentFragment();
Object.values(dptosLocs["Salto"]).forEach(function(dptosLoc, index) {
var opt = document.createElement('option');
opt.innerHTML = dptosLoc;
opt.value = dptosLoc;
fragment.appendChild(opt)
sel.appendChild(fragment);
});
}
}
FORM VALIDATION:
function validar (){
var name, lastName, email, dpto, location, ci, condictions, expresion;
name = document.getElementById('name').value;
lastName = document.getElementById('lastName').value;
email = document.getElementById('email').value;
dpto = document.getElementById('dpto').value;
location = document.getElementById('location').value;
ci = document.getElementById('ci').value;
conditions = document.getElementById('conditions').value;
if (name === ""){
alert("El campo nombre está vacío");
}
}
The problem with your script is that the validar() function is never called.
Please, remember, if you write a function and you never call it in your code, it will never be executed.
What you have to do is to add the call to your validar() function in the onsubmit event of the form.
<form action="/" id="form" action="GET" onsubmit="return validar();">
And your validar() function should return false if the validation is not verified for the form.
if (name === ""){
alert("El campo nombre está vacío");
return false;
}
return true;
You should take a look at how events are called in javascript when dealing with forms.
You're missing the call to the validar function
<form .... onsubmit="return validar()">
Also validar should return false if the validation fails and true if it passes
Related
I have below code where I add new form after clicking button. If I put some values into the fields everything is reseted. I would like to prevent that.
I tried e.preventDefault() and return false but it's not working as I would like to.
Additionally after clicking 'add button' I am taking data from json file.
Please see my code here. Any help will be appreciated.
// add new product to the list
const newLocal = document.querySelector('.add-product-button');
const addNewProduct = newLocal;
const listProduct = document.querySelector('.products-list');
const changeVisibility = document.getElementById('change-visibility');
let productCounter = 1;
addNewProduct.addEventListener('click', e => {
e.preventDefault();
productCounter++;
generateTemplate();
changeVisibility.style.display = 'block';
});
const generateTemplate = (e) => {
const html = `
<li>
<div class="first-product-indicator">
<div class="first-product-border-line"></div>
<div class="product-number">${productCounter}</div>
</div>
<form action="" method="get" class="form-product">
<select name="product-type" id="product-type" class="" required>
<option value="" disabled selected hidden>Typ Produktu</option>
<option value="produkt" >PRODUKT GOTOWY</option>
<option value="materiały" >MATERIAŁY POMOCNICZE</option>
<option value="surowce" >SUROWCE</option>
</select>
<div class="product-container">
<select name="product" id="product" class="option-field product-list" required>
<option value="" disabled selected hidden>Produkt</option>
</select>
<i class="fas fa-plus-circle add-product"></i>
</div>
<div class="form-price">
<input type="number" id="quantity" name="quantity" placeholder="Ilość">
<input type="number" id="netto" name="netto" placeholder="Netto">
<input type="number" id="brutto" name="brutto" placeholder="Brutto">
</div>
<div class="form-total-price">
<input type="number" id="netto-total" name="netto-total" placeholder="Wartość netto">
<input type="number" id="brutto-total" name="brutto-total" placeholder="Wartość brutto">
</div>
</form>
</li>
`;
listProduct.innerHTML += html;
// populate product select field with values from json file (finished_good.json)
let newProductElement = document.querySelector('.products-list').lastElementChild;
let dropdownProductAdd = newProductElement.querySelector('.product-list');
dropdownProductAdd.length = 0;
let defaultOptionProductAdd = document.createElement('option');
defaultOptionProductAdd.text = 'Produkt';
dropdownProductAdd.add(defaultOptionProductAdd);
dropdownProductAdd.removeIndex = 0;
const urlProductAdd = 'finished_good.json';
const requestProductAdd = new XMLHttpRequest();
requestProductAdd.open('GET', urlProductAdd, true);
requestProductAdd.onload = function() {
if (requestProductAdd.status === 200) {
const dataProductAdd = JSON.parse(requestProductAdd.responseText);
let optionProductAdd;
for (let i = 0; i < dataProductAdd.length; i++) {
optionProductAdd = document.createElement('option');
optionProductAdd.text = dataProductAdd[i].name;
dropdownProductAdd.add(optionProductAdd);
}
} else {
// Reached the server, but it returned an error
}
}
requestProductAdd.onerror = function() {
console.error('An error occurred fetching the JSON from ' + urlProductAdd);
};
requestProductAdd.send();
e.preventDefault();
};
I have an array in Javascript that consists of three different countries. I have a form in my HTML page that contains a drop down box. Instead of populating the drop down box using
<option value=""> *option name* </option>,
I want to try including the elements of my array in my drop down box, so when the user clicks it, they'll see the elements.
var countries=["Sri Lanka","Bangladesh","India"]
I tried using the 'onclick' function in my HTML so that it would link to this following function
function myFunction() {document.getElementById('Bangladesh').innerhtml= (countries[2])>
But I since removed it since it didn't work. How exactly can I populate the drop down box with elements from my array. My JS and HTML code have been provided below.
<DOCTYPE html>
<head>
<script src="inquiries.js"> </script>
</head>
<body>
<h1 align="center"class='header1'> <font size="8"> </font> </h1>
<div class="busybox">
<form name="myForm" form action="/action_page.php" onsubmit="return validateForm();" method="post">
<label for="fname"> <b> First Name </b> </label>
<input type="text" id="fname" name="firstname" placeholder="Your name......"
required >
<label for="Birthday"> <b> E-Mail </b> </label>
<input type="text" id="email" name="email" placeholder="Enter your E-mail address....." >
<Label for="country"> <b> Country </b> </Label>
<select id="country" name="country">
<option value="Sri Lanka"> Sri Lanka </option>
<option value="India"> India </option>
<option value="Bangladesh"> <p id="bangladesh"> </p> </option>
</select>
<label for="summary"> <b> Summary </b> </label>
<textarea id="summary" name="Summary" placeholder="Write a summary of your inquiry
here...." style="height:200px"> </textarea>
<input type="submit" value="submit" id="sbox" onclick="myfunction()">
</form>
----JS CODE----
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}else{
return true;
} }
var countries = ["Sri Lanka", "India", "Bangladesh"];
function myFunction() {document.getElementById('Bangladesh').innerhtml =(countries[2])>
var countries=["Sri Lanka","Bangladesh","India"];
document.getElementById("Select").innerHTML = "";
for(var i=0;i<countries.length;i++)
{
var node = document.createElement("option");
var textnode = document.createTextNode(countries[i]);
node.appendChild(textnode);
document.getElementById("Select").appendChild(node);
}
<select id="Select"></select>
Here is a solution using array#foreach.
var select = document.getElementById("selectCountry");
var countries = ["Sri Lanka", "India", "Bangladesh"];
countries.forEach((country) => {
var element = document.createElement("option");
element.textContent = country;
element.value = country;
select.appendChild(element);
});
<select id="selectCountry"></select>
Try this:
$('#country').change(function(){
var dropdown=document.createElement('select');
var options="";
for(i = 0; i < countries.length; i = i+1){
options+= "<option value='"+countries[i]+"'>"+countries[i]+"</option>";
}
dropdown.innerHTML= options;
document.getElementById('country').appendChild(dropdown);
});
To do it with jQuery:
$(document).ready(function() {
var select = $('#country');
var countries = ["Sri Lanka", "India", "Bangladesh"];
for (var i=0; i<countries.length; i++) {
var country = countries[i];
var el = $("<option value='" + country + "'>" + country + "</option>");
$(select).append(el);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<Label for="country"> <b> Country </b> </Label>
<select id="country" name="country">
How to Enable/Disable input field based on a dropdown selection. and also I should take the user data in JSP based on the selection.
<form action="../jsp/findActorbyChar.jsp">
<h3>Search by:
<select name ="nameField"> </h3>
<option> Only FirstName </option>
<option> Only LastName </option>
<option> Or </option>
<option> And </option>
</select>
<br><br>
First Name <input type="text" name="firstName"/>
Last Name <input type="text" name="lastName"/>
<br><br>
<input type="submit"/>
<input type="reset"/>
Modified Html as shown below:
<h3>Search by:</h3>
<select name ="nameField" id="nameField">
<option>Only FirstName</option>
<option>Only LastName</option>
<option>Or</option>
<option>And</option>
</select>
<br><br>
First Name <input type="text" name="firstName" id="firstNameInput"/>
Last Name <input type="text" name="lastName" id="lastNameInput" />
<br><br>
<input type="submit"/>
<input type="reset"/>
Javascript code:
var nameField = document.getElementById("nameField");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
nameField.addEventListener("change", function(){
//Update this to your logic...
if(nameField.value === "And"){
firstNameInput.disabled = true;
lastNameInput.disabled = true;
}
});
But I think it would be easier if using JQuery to handle DOM update.
Give your menu an id and then you can access the selected index with menu.options.selectedIndex. From there, you can add an on change handler to the menu and use switch cases to set the disabled attribute of the menu.
<h3>Search by:
<select id="menu" name ="nameField"> </h3>
<option> Only FirstName </option>
<option> Only LastName </option>
<option> Or </option>
<option> And </option>
</select>
<br><br>
First Name <input id="first" type="text" name="firstName"/>
Last Name <input id="last" type="text" name="lastName"/>
<br><br>
<input type="submit"/>
<input type="reset"/>
<script type="text/javascript">
var menu = document.getElementById('menu');
var first = document.getElementById('first');
var last = document.getElementById('last');
menu.onchange = function(){
var enableFirst = false, enableLast = false;
switch(menu.options.selectedIndex){
case 0:
enableFirst = true;
enableLast = false;
break;
case 1:
enableFirst = false;
enableLast = true;
break;
case 2:
/*not sure which results you want here*/
break;
case 3:
/*not sure which results you want here*/
break;
default:
break;
}
first.disabled = !enableFirst;
last.disabled = !enableLast;
}
</script>
My code: still all the input fields are enabled
enter code here
<script src="script.js">
var nameField = document.getElementById("nameField");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
nameField.addEventListener("change", function(){
//Update this to your logic...
<script src="script.js">
var nameField = document.getElementById("nameField");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
nameField.addEventListener("change", function(){
//Update this to your logic...
if(nameField.value === "And"){
firstNameInput.disabled = true;
lastNameInput.disabled = true;
}
else if(nameField.value === "firstNameInput"){
firstNameInput.disabled = false;
lastNameInput.disabled = true;
}
else if(nameField.value === "lastNameInput"){
firstNameInput.disabled = true;
lastNameInput.disabled = false;
}
elseif(nameField.value === "lastNameInput"){
firstNameInput.disabled = true;
lastNameInput.disabled = true;
}
});
</script>
the select option will not update till i add the innerHTML again.
function myFunction() {
for (index = 0; index < array.length; ++index) {
var bAccount = array[index].id;
var selectban = document.getElementById(bAccount);
var selectaccount2 = document.getElementById("AccountToUse1");
var opt = document.createElement('option');
opt.value = selectban.value;
opt.innerHTML = selectban.value;
selectban.value = "test";
selectaccount2.appendChild(opt);
}
}
i am stepping thorugh multiple input fields and gathering the values, these are then added to a new option element. when i appendChild to the selectaccount2 which is the select element, this does not insert the value. any ideas?
<!-- Text input-->
<div id="details" style="display: none;">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="accountNumber">Account Number</label>
<div class="col-md-4">
<input id="accountNumber" name="accountNumber" type="text" placeholder="your game account number" class="form-control input-md" required="" onchange="myFunction()">
</div>
</div>
</div>
<div id="DetailsFooter" style="display: none;">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">details</label>
<div class="col-md-4">
<select id="AccountToUse" name="AccountToUse" type="text" placeholder="" required="">
</select>
</div>
</div>
</div>
<fieldset id="DetailsView" class="DetailsView">
<h2>Details Applicant 1</h2>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="Accounts">How many accounts do you have?</label>
<div class="col-md-4">
<select id="Accounts" name="Accounts" class="form-control" onchange="amountchanged()">
<option value="0">Please Select an Amount</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</div>
<div id="DetailsContainer">
</div>
</fieldset>
<script>
var select = document.getElementById("Accounts"),
container = document.getElementById("DetailsContainer");
var array = [];
var accountToUse;
var footer;
var num = 0;
function changeId(nodes, n) {
for (var i = 0; i < nodes.length; i = i + 1) {
if (nodes[i].childNodes) {
changeId(nodes[i].childNodes, n);
}
//if id value is 'accountNumber', change it
if (nodes[i].id && /^ch$|^accountNumber$/i.test(nodes[i].id)) {
nodes[i].id += String(n);
array.push(nodes[i]);
}
}
}
function amountchanged() {
var amount = select.value,
obj = document.getElementById("details").cloneNode(true),
children = obj.childNodes;
footer = document.getElementById("DetailsFooter");
container.innerHTML = "";
var count;
num += 1;
obj.id = obj.id + num;
if (num < 16) {
changeId(children, num);
}
document.body.appendChild(obj);
for (count = 1; count <= amount; count++) {
var heading = "<h3>" + count + " Details</h3>"
container.innerHTML += heading;
container.innerHTML += obj.innerHTML;
}
accountToUse = footer.getElementsByTagName("select")[0];
accountToUse.id = 'AccountToUse1';
container.innerHTML += footer.innerHTML;
}
function myFunction() {
for (index = 0; index < array.length; ++index) {
var bAccount = array[index].id;
var select22 = document.getElementById(bAccount);
var selectaccount2 = document.getElementById("AccountToUse1");
var opt = document.createElement('option');
opt.value = select22.value;
opt.innerHTML = select22.value;
select.value = "test";
selectaccount2.appendChild(opt);
}
}
</script>
Although I've seen people recommend adding an option the way you have there, so presumably it works on many if not most browsers, the most robust, reliable way I've ever found is the Option constructor and the add method:
selectaccount2.options.add(new Option(selectban.value));
If you just provide the value (the first argument), the text and value will be the same. If you give two arguments, the first is the text and the second is the value.
Live copy:
var array = [{
id: "one"
}, {
id: "two"
}, {
id: "three"
}];
function myFunction() {
for (var index = 0; index < array.length; ++index) {
var bAccount = array[index].id;
var selectban = document.getElementById(bAccount);
var selectaccount2 = document.getElementById("AccountToUse1");
var opt = document.createElement('option');
opt.value = selectban.value;
opt.innerHTML = selectban.value;
selectban.value = "test";
selectaccount2.appendChild(opt);
}
}
myFunction();
<select id="AccountToUse1" size="4"></select>
<input type="hidden" id="one" value="uno">
<input type="hidden" id="two" value="due">
<input type="hidden" id="three" value="tre">
Side note: You're falling prey to The Horror of Implicit Globals: Declare index.
I have a form in HTML and that if the fields are left blank, the Javascript will print inside the fields error. Please can some one give me a piece of code that will validate the form and then will print Error on top of the form if its left blank and not inside the fields of the form?
My Form:
<form id="contact" onsubmit="checkContactForm(); return false;" onreset="resetForm();">
<p>Fill in the form below to send me a message!</p>
<div id="errormessage"></div>
<p>
<label for=""> </label>
<input type="text" name="" id="" onfocus="" />
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" onfocus="resetField(this);" />
</p>
<p>
<label for="email">E-mail address:</label>
<input type="text" name="email" id="email" onfocus="resetField(this);" />
</p>
<p>
<label for="message">Your Message:</label>
<textarea name="message" id="message" rows="5" cols="25" onfocus="resetField(this);"></textarea>
</p>
<p>
<button type="submit">Send Message</button>
<button type="reset">Reset Form</button>
</p>
My Javascript:
var requiredFields = ["name", "email", "message"];
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "";
var emptyFields = true;
}
}
if (!emptyFields) { myForm.submit(); }
}
function resetField(myField) {
if (myField.value == "Error") {
myField.style.color = "#000";
myField.value = "";
}
}
function resetForm(myForm) {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
myForm[fieldName].style.color = "#000";
}
}
Since HTML5 there is a form-validation API (http://www.w3schools.com/js/js_form_validation.asp)
Here you can find a pretty good "tutorial": http://www.smashingmagazine.com/2009/07/07/web-form-validation-best-practices-and-tutorials/
If I've understand you want the error will be printed in the #errormessage div, right?
If so you can simply do something like this:
function addError(str){
document.getElementById("errormessage").innnerHTML = document.getElementById("errormessage").innerHTML + str + "<br>";
}
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "";
var emptyFields = true;
addError(fiedlName+" is empty!");
}
}
if (!emptyFields) { myForm.submit(); }
}