I'm learning basic web development and I'm VERY, VERY stuck on JavaScript form validation and loops. I need to validate radio buttons, drop down selection, checkboxes, number selector, and a box to type in your name. I think I'm on the right track for some of it but I could be completely wrong. I have 0 idea how to do a number selector (pin number between 1000-9999). The loop needs to read all the form fields and display their value in the console when submit button is pressed and validation passes. I've tried finding this stuff everywhere and have struggled a lot. I'll leave the code for each below, This is also my first post on here so if you need more info to help me please just let me know!
For the enter your name box
function validateForm() {
let x = document.forms["whatisyourname"]["name"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Radio button
function validateForm() {
var radios = document.getElementsByName("hair_color");
var formValid = false;
var i = 1;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Please select a hair option");
return formValid;
}
Drop Down
function validate() {
var ddl = document.getElementById("food");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "")
{
alert("Please select a food");
}
}
Check Boxes
function valthisform() {
var checkboxs=document.getElementsByName("hobby");
var okay=false;
for(var i=1,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
else alert("Please check 2 checkboxes");
}
Aucun commentaire:
Enregistrer un commentaire