Hi am new to Javascript and don't know how to validate my check-boxes I have looked up many examples but still don't understand it can someone please tell me how to validate it and also my drop down menu inst validating at all any help in advance will be appreciated.
My Java Script and HTML
function validateForm(){
var fname, lname, sex, address, email, length, songs, a, i, check, error;
a=0;
check=false;
error=false;
fname=document.getElementById("firstname").value;
lname=document.getElementById("lastname").value;
sex=document.getElementsByName("sex");
address=document.getElementById("address").value;
email=document.getElementById("email").value;
length=document.getElementById("len").value;
// songs=document.getElementByName("f_song");
if(fname=="" || fname==null){
alert("please input a first name");
error=true;
return false;
}
if(lname=="" || lname==null){
alert("please input your last name");
error=true;
return false;
}
for(i=0; i<sex.length; i++){
if(sex.item(i).checked==false){
a++;
}
}
if(a==sex.length){
alert("Please select Male or Female");
error=true;
return false;
}
if(address=="" || address==null){
alert("Please input your address thanks");
error=true;
return false;
}
if(email=="" || email==null){
alert("Please enter a email address");
error=true;
return false;
}
if(length=="" || length==null){
alert("Be select how long have you been a fan");
error=true;
return false;
}
alert("Am working ");
}
MY HTML
<head>
<title>] </title>
<link rel="stylesheet" type="Text/css" href="wit_frm.css"/>
<script type="text/javascript" src="java.js">
</script>
</head>
<body>
<div id="container">
<div id="header">
</div>
<div id="topnav">
<div id="link">
Home
Fan Site
Register
</div>
</div>
<div id="contentarea">
<form method="post" action="" onsubmit= "return validateForm();">
<fieldset>
<legend>Personal Information</legend>
First Name:<input type="text" name="fname" id="firstname"/>
<br/>
<br/> Last Name:<input type="text" name="lname" id="lastname"/>
<br/>
<br/> Sex: <input type="radio" name="sex" id="m"/>Male <input type="radio" name="sex" id="f"/>Female
<br/>
<br/>Address: <textarea id="address" name="add" rows="4" cols="30"></textarea>
</fieldset>
<fieldset>
<legend> User Information</legend>
<br/>Email: <input type="text" name="e_address" id="email"/>
<br/>
<br/>No of years listening to her music: <select name="n_years" id="len">
<option value="less than a yr"> less than 1yr</option>
<option value="2-5 years">2-5 years</option>
<option value="5+ years">5+ years</option>
</select>
<br/>
<br/>Favorite Songs:I will always love you<input type="checkbox" name="f_song" value="I will always love you"/> I look to you<input type="checkbox" name="f_song" value="I look to you"/></p>
<br/> I have nothing<input type="checkbox" name="f_song" value="I have nothing"/> One moment in time<input type="checkbox" name="f_song" value="one moment in time"/></p>
<br/> I wanna dance with somebody<input type="checkbox" name="f_song" value="I wanna dance with somebody"/> Greatest Love of All<input type="checkbox" name="f_song" value="Greatest love of all"/></p>
</fieldset>
<br/><input type="submit" name="sub_button" value="SUBMIT"/> <input type="reset" name="res_button" value="CLEAR"/>
</form>
</div>
<div id="footerfix">
</div>
<div id="footer">
<div id="link_1">
Home
Fan Site
About Her
</div>
</div>
</div>
</body>
</html>
I would do it like this:
Bin example
var f_song = document.getElementsByName("f_song");
var oneSongSelected = 0;
//Loop through the checkbox elements, and tally the selected
for(var ss = 0; ss < f_song.length; ss++){
if(f_song[ss].checked){
oneSongSelected++;
}
}
//If none are selected, then alert your error, and return false
if(oneSongSelected === 0){
alert("Please select at least one song");
return false;
}
You could use jquery, but you can do something like this:
In your html code, you can use the first dropdown option "Select" and value "-1":
<select id="dropDown">
<option value="-1">Select</option>
</select>
CheckBox:
<input type="checkbox" name="checkbox" id="checkbox" />
DropDown JavaScript:
var aValue;
aValue = document.getElementById("dropDown").value;
if(aValue == "-1"){
return false;
}
CheckBox JavaScript:
var checkbox = document.getElementById('checkbox');
if(!checkbox.checked){
return false;
}
as you are new in JavaScript, I recommend that you to learn jQuery, it's easier and simpler than JavaScript. If you have checkboxes and you want to validate them, you can try this:
$('#checkbox').click(function(){
if (this.checked) {
}
});
Explanation of Code
$('#checkbox').click(function() => this line says "when the element with id of #checkbox is clicked, do the stuff inside this function." You will need to replace #checkbox with the id of your checkbox (example: #yourCheck) or its class (example: .yourClass).
if (this.checked) => this if statement checks to see if the element is checked or not. You should include your code for when the checkbox is checked inside of the brackets.
EDIT: Here is a JSFiddle example that I made.
Related
I want to check if the Value enter in the input is in the datalist.
If not i inform that the value is not in the list, I write something but the submit is done anyway, i miss something ?
Edit: I edit to have a trial form. If i enter productD the submit can't not be done becuase is not in the list defined.
<tbody>
<div class="fichetechniquediv">
<form action="{% url 'createdfichetechnique' %}" method='post' onclick="return myCheckFunction(this)">
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlist" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="productA">productA</option>
<option value="productB">productB</option>
<option value="productC">productC</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
</div>
</tbody>
<script>
function myCheckFunction(form) {
var list = document.getElementsById("productslist");// get the values that are currently under the datalist tag in option tags
var val = document.getElementsByName("Product");// get the user input
if( list.include(val)){ // compare the options with the user input
submit(form)}// if one is equal with the user input submit the form with the method submit();
else{
return false// else don't submit the form, the user will have to change his input
}
}
</script>
Example productD
const list = document.querySelector("#productslist")
const btn = document.querySelector(".buttonsave")
console.log(list.options.length)
if(list.options.length <= 0 ){
btn.disabled = true
}else {
btn.disabled = false
}
Check if is any products. If the script can't see any products disable the button to send. I hope I helped
You cannot use include for DOM elements like you do.
Also you have duplicate IDs
Instead do this:
const list = document.querySelectorAll("productslist option")
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = document.getElementById("productlistInput").value
const found = [...list].find(opt => opt.value===val)
if (!found) {
alert("Please choose an existing value");
e.preventDefault();
}
})
<form id="myForm" action="..." method='post'>
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlistInput" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="prod1">Product 1</option>
<option value="prod2">Product 2</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
There are two things going wrong in this:
document.getElementsById("productslist"); is incorrect. The function is getElementById(...)
document.getElementById("productslist"); will get you an HTML nodes, not the values.
One of the ways to get the values is:
const values = [];
Array
.from(document.getElementById("productslist").options)
.forEach((option) => {
values.push(option.value);
}
Now that you have the values in the values array, you can look it up to check if the value is already present.
I need help to validate a form on submit. It should check that one of more checkboxes are selected or else display error message. I have currently got it working but the problem is the checkbox option is displayed after selecting a radio button on the form.
The code I have now still shows an error message even if the div isn't displayed which is a big issue as users haven't seen the checkbox option.
I want the checkbox error message to show ONLY if the user has selected the radio button "NO" and therefor is required to check a checkbox. If they select the radio button "YES" and this checkbox div is not displayed, then I don't want the error message on submit.
function hide() {
document.getElementById('hidden').style.display ='none';
}
function show() {
document.getElementById('hidden').style.display = 'block';
}
function validateForm() {
var checked = false;
var elements = document.getElementsByName("tick");
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
checked = true;
}
}
if (!checked) {
alert('You must select why you are attending!');
}
return checked;
}
<form id="form" method="post" enctype="text/plain" name="vform">
<p>This course is identified in my Work Plan and Learning Agreement</p>
<input type="radio" name="optionOne" value="yes" onclick="hide()" required> Yes<br>
<input type="radio" id="chk" name="optionOne" value="no" onclick="show()"> No<br>
<p>
<div id="hidden" style="display: none">
<p>I am attending this session because (tick all that apply) </p>
<input type="checkbox" name="tick" value="selectone"> It will help me develop the skills and knowledge required for my current role<br>
<input type="checkbox" name="tick" value="selecttwo"> It will help me develop the skills and knowledge for a possible future role/body of work <br>
<input type="checkbox" name="tick" value="selectthree"> It was identified as a need during my performance management discussions<br>
<input type="checkbox" name="tick" value="selectfour"> My manager recommended that I attend<br>
<input type="checkbox" name="tick" value="selectfive"> I am interested in the content<br>
<p>
<p>What would you like to achieve as a result of your attendance? For example, "I would like to learn to write better emails to improve my communication skills." </p>
<input type="text" id="results" name="results">
</div>
<div class="submit-button">
<button type="submit" name="submit" onclick="validateForm()" value="send">Submit</button>
</div>
</form>
try (select "No" below)
function validateForm(e) {
let inp=[...document.getElementsByName("tick")];
if(!inp.some(i=>i.checked) && chk.checked) {
e.preventDefault();
alert('You must select why you are attending!');
}
}
function validateForm(e) {
let inp=[...document.getElementsByName("tick")];
if(!inp.some(i=>i.checked) && chk.checked) {
e.preventDefault();
alert('You must select why you are attending!');
}
}
// DISPLAY HIDDEN TEXT
function hide() {
document.getElementById('hidden').style.display ='none';
}
function show() {
document.getElementById('hidden').style.display = 'block';
}
<form id="form" method="post" enctype="text/plain" name="form">
<p>This course is identified in my Work Plan and Learning Agreement</p>
<input type="radio" name="optionOne" value="yes" onclick="hide()" required> Yes<br>
<input type="radio" id="chk" name="optionOne" value="no" onclick="show()"> No<br>
<p>
<div id="hidden" style="display: none">
<p>I am attending this session because (tick all that apply) </p>
<input type="checkbox" name="tick" value="selectone"> It will help me develop the skills and knowledge required for my current role<br>
<input type="checkbox" name="tick" value="selecttwo"> It will help me develop the skills and knowledge for a possible future role/body of work <br>
<input type="checkbox" name="tick" value="selectthree"> It was identified as a need during my performance management discussions<br>
<input type="checkbox" name="tick" value="selectfour"> My manager recommended that I attend<br>
<input type="checkbox" name="tick" value="selectfive"> I am interested in the content<br>
<p>
<p>What would you like to achieve as a result of your attendance? For example, "I would like to learn to write better emails to improve my communication skills." </p>
<input type="text" id="results" name="results">
</div>
<div class="submit-button">
<button type="submit" onclick="validateForm(event)" name="submit" value="send">Submit</button>
</div>
</form>
Here's the old school way. Just check the display attribute of the div, and only set your flag to false inside that.
function validateForm() {
var checked;
if(document.getElementById("hidden").style.display == "block") {
checked = false;
var elements = document.getElementsByName("tick");
for (var i=0; i < elements.length; i++) {
if (elements[i].checked) {
checked = true;
}
}
}
if (checked===false) {
alert('You must select why you are attending!');
}
return checked;
}
edit: I don't think the similar question mentinoed in the comments can help :(. Unless I'm just really bad at this... I can get a simple alert message to come up but can't get the alert for the the individual radio button to show.
I'm just doing a simple form with radio buttons with Javascript to give an alert after hitting submit when one of the choices is chosen. I'm brand new to Javascript so I'm not sure what else I can do...
The HTML works but the function inside of it doesn't at all. I'm lost on what else to do. Any advice would be really appreciated.
<!DOCTYPE html>
<html>
<head>
<title> Gender Check </title>
<meta charset ="UTF-8">
</head>
<body>
<form id= "form" name ="form" onsubmite="gender()">
<label>Male
<input type="radio" id="male" name="male"/>
</label>
<label>Female
<input type="radio" id="female" name="female"/>
</label>
<label>Trans
<input type="radio" id="trans" name="trans"/>
</label>
<label>Alien
<input type="radio" id="alien" name="alien"/>
</label>
<label>Boeing AH-64 Apache Attack Helicopter
<input type="radio" id="helicopter" name="helicopter"/>
</label>
<input type="submit" name="submit" value="Don't lie to me."/>
</form>
<script type="text/javascript">
function gender() {
var male=document.form[0].element[0];
var female=document.form[0].element[1];
var trans=document.form[0].element[2];
var alien=document.form[0].element[3];
var helicopter=document.form[0].element[4];
if (document.getElementById('male').checked == true)
{
alert("You are a Male.")
}
else if (document.getElementById('female').checked == true)
{
alert("You are a Feale.")
}
else if (document.getElementById('trans').checked == true)
{
alert("You are Trans.")
}
else if (document.getElementById('alien').checked == true)
{
alert("You are an...uh...Alien?")
}
else if (document.getElementById('helicopter').checked == true)
{
alert("You are definitely not a four-blade, twin-turboshaft attack helicopter with a tailwheel-type landing gear arrangement and a tandem cockpit for a two-man crew.")
}
else
{
alert("Please pick a choice")
}
}
document.forms[0].onsubmit = gender;
</script>
</body>
</html>
The errors were :
You used document.form[0].element[1] instead of document.form[1]
You wrote onsubmite instead of onsubmit
All your radio input had the same name attribute thus you were able to select multiple choices. You should use the same name for each radio button of the same group
You can reduce male.checked == true with male.checked alone
function gender() {
var male = document.form[0];
var female = document.form[1];
var trans = document.form[2];
var alien = document.form[3];
var helicopter = document.form[4];
if (male.checked) {
alert("You are a Male.")
} else if (female.checked) {
alert("You are a Female.")
} else if (trans.checked) {
alert("You are Trans.")
} else if (alien.checked) {
alert("You are an...uh...Alien?")
} else if (helicopter.checked) {
alert("You are definitely not a four-blade, twin-turboshaft attack helicopter with a tailwheel-type landing gear arrangement and a tandem cockpit for a two-man crew.")
} else {
alert("Please pick a choice")
}
}
<!DOCTYPE html>
<html>
<head>
<title>Gender Check</title>
<meta charset="UTF-8">
</head>
<body>
<form id="form" name="form" onsubmit="gender()">
<label>Male
<input type="radio" id="male" name="choice" />
</label>
<label>Female
<input type="radio" id="female" name="choice" />
</label>
<label>Trans
<input type="radio" id="trans" name="choice" />
</label>
<label>Alien
<input type="radio" id="alien" name="choice" />
</label>
<label>Boeing AH-64 Apache Attack Helicopter
<input type="radio" id="helicopter" name="choice" />
</label>
<input type="submit" name="submit" value="Don't lie to me." />
</form>
</body>
</html>
NOTE
Instead of document.form[0]; (first element of the form) you can use document.form.choice[0] which will look for the list of radio and select the first one [0]
<form id= "form" name ="form" onsubmit="gender()">
You need to associate an event known as onsubmit which will call gender() function when form is submitted.
You can prevent the submission by returning false via function and for that you will need to do something like this
onsubmit="return gender()"
If you want to submit form, change the button type to button and associate an event as onclick='gender()' and keep rest of the code unchanged.
I have created a form and I am looking to get the data the user entered. The javascript I have, so far pulls in all the data. I am having an issue with pulling the data of the selected radio button. I read some articles and they say the 'name' needs to be the sames but this doesn't work and if I give it unique 'ID's then selecting one or the other radio buttons doesn't work. Also I can't use jQuery
js
var myNodeList = document.getElementsByName('cf');
var myArray = []; // empty Array
for (var i = 0; i < myNodeList.length; i++) {
if(i<4)
for ( i; i < 3; i++) {
var self = myNodeList[i].value;
myArray.push(self);
}
else if(i==4)
myArray.push(document.getElementById('status').value);
else if(i==5)
myArray.push(document.getElementById('subscribe').value);
else if(i==6)
myArray.push(document.getElementsByName('support')[i]);
else if(i==7)
for ( i; i < myNodeList.length; i++) {
var self = myNodeList[i].value;
myArray.push(self);
}
}
console.log(myArray)
html
<!DOCTYPE html>
<html>
<head>
<title>Contact Me</title>
<link rel="stylesheet" type="text/css" href="contactform_Lab8.css">
</head>
<body>
<form id="contactus">
<fieldset>
<label for="name">Name:</label>
<input id="name" type="text" name="cf" autofocus required>
<label for="email">Email:</label>
<input id="email" type="email" name="cf" required>
<label for="phone">Phone:</label>
<input id="phone" type="tel" name="cf" required>
<label for="status">Status:
<select id="status" name="cf" required>
<option value="client">Client</option>
<option value="partner">Partner</option>
<option value="vendor">Vendor</option>
</select>
</label>
<label for="subscribe">
<input id="subscribe" type="checkbox" name="cf" value="check" checked>
Send me your newsletter</label>
<label for="sales">
<label for="support">
<input id="sales" type="radio" name="slsSupport" value="sales" checked>Sales
<input id="support" type="radio" name="slsSupport" value="support">Support
</label>
</label>
<label for="msg">Message:</label>
<textarea id="msg" name="cf" rows="10" cols="30" required></textarea>
</fieldset>
<fieldset>
<button type="submit">Send</button>
<button type="reset">Reset</button>
</fieldset>
</form>
<script src="contactform_Lab8.js"></script>
</body>
</html>
ID names are unique and should not be used twice in the same page. You can get the value from only checked radio buttons like this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'radio') {
if (inputs[i].checked){
alert('Checked radio buttons value is:' + inputs[i].value);
}
}
}
In Jquery
$("input[name=slsSupport]:checked").val();
In plain js you would want to find all the radio buttons, give each radio button an Id then select them one by one:
function GetSelected() {
for(var i=0;i<2;i++) {
var element = document.getElementById('radio'+i);
if (element.checked === true)
return element
}
}
An ID must be unique in all the HTML document. To group inputs (radio for exemple) you have to give them the same name (not ID).
To find the value with JQuery look this question and for pure JS solution look this other question.
Please bear with me as I am a beginner when it comes to JavaScript !
I have a dymamic form that pulls information from a database. For each line in the database there is a new row of form fields and the select name incorporates the id from the database - this is all on the same form e.g
<select name="supplier<%=objRst.fields("returnpartid")%>" id="supplier<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="STOCKACTION<%=objRst.fields("returnpartid")%>" id="STOCKACTION<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="stockreason<%=objRst.fields("returnpartid")%>" id="stockreason<%=objRst.fields("returnpartid")%>">
<select name="creditaction<%=objRst.fields("returnpartid")%>" id="creditaction<%=objRst.fields("returnpartid")%>" onchange="validatelink3(<%=objRst.fields("returnpartid")%>)">
<select name="rejectreason<%=objRst.fields("returnpartid")%>" id="rejectreason<%=objRst.fields("returnpartid")%>">
Users are currently missing out data when they are saving the record and I want to prevent this, The save button saves ALL of the records in one go so some lines will be totally blank if they have not yet been processed.
If a user has started to fill in the row but not completed all the information for that record then I need to stop the form submission.
Take a look at Parsley. I use this to validate my login and create user page of my website. Let me know what you think of it!
This is a great javascript tool that utilizes jQuery to validate different forms. Its really nice as you can have it validate several different things such as max and or min text length. It is very easy to implement because all you need to do is add the identifiers to the HTML element.
EDIT:
To avoid a link only answer, here is the code that could be helpful.
<form id="demo-form" data-parsley-validate>
<label for="question">Do you code? *</label>
<p>
<input type="radio" name="question" value="true" required /> Yes
<input type="radio" name="question" value="false" /> No
</p>
<label for="languages">If yes, in which language(s)?</label>
<input type="text" class="form-control" name="languages" data-parsley-conditionalrequired='[" [name=\"question1\"]:checked", "yes"]' data-parsley-validate-if-empty data-parsley-success-class="" data-parsley-conditionalrequired-message="This value is required since you are a programmer!" />
<label for="question">Do you eat dog food? *</label>
<p>
<input type="radio" name="question2" value="yes" required /> Yes
<input type="radio" name="question2" value="no" /> No
</p>
<label for="why">If no, why?</label>
<input type="text" class="form-control" name="why" data-parsley-conditionalrequired='[" [name=\"question2\"]:checked", "no"]' data-parsley-validate-if-empty data-parsley-success-class="" data-parsley-conditionalrequired-message="This value is required since you do not eat dog food!" />
<input type="submit" class="btn btn-default pull-right" />
</form>
<script type="text/javascript">
window.ParsleyConfig = {
validators: {
conditionalrequired: {
fn: function (value, requirements) {
// if requirements[0] value does not meet requirements[1] expectation, field is required
if (requirements[1] == $(requirements[0]).val() && '' == value)
return false;
return true;
},
priority: 32
}
}
};
</script>
<script type="text/javascript" src="../../dist/parsley.js"></script>
EDIT 2:
This is also a simple html file that could do something close to what I think that you want:
<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<input id="test" type="checkbox" id="chk"/>asdfad
<form>
<textarea></textarea>
<button onclick="myFunction()">asd</button>
<form>
<p>If the check box is check the thing is required and if the box is not check then it is not required. So tell your form to only save the rows that have the box checked?</p>
<script>
function myFunction() {
if(document.getElementById("test").checked){
document.getElementsByTagName("textarea")[0].setAttribute("required", "true");
}
else{
document.getElementsByTagName("textarea")[0].removeAttribute("required");
}
}
</script>
</body>
</html>