JavaScript Form Validation not working entirely - javascript

I am trying to have JavaScript code validate all the elements of this form but for some reason the select box doesn't validated. The user can fill in all the blanks except for the select box and the JavaScript does not catch it. Any ideas as to what I am missing? Thanks.
<script type="text/javascript">
function validateForm() {
var ageErr = document.getElementById('ageErr');
var nameErr = document.getElementById('nameErr');
var radioErr = document.getElementById('radioErr');
var results = document.getElementById('results');
var theName = document.formContact.theName;
var theAge = document.formContact.theAge;
var theRadioGp = document.formContact.contact;
var theSelect = document.formContact.theSelect;
var chkValue;
if(theName.value =="") {
nameErr.innerHTML = "A name is required ";
theName.focus();
return false;
}else {
nameErr.innerHTML= "";
}
if(theAge.value ==""){
ageErr.innerHTML = "An age is required";
theAge.focus();
return false;
}else {
nameErr.innerHTML = "";
}
if(theAge.vale =="") {
age.Err.innerHTML = "An age is required";
theAge.focus();
return false;
} else if (isNaN(theAge.value)) {
ageErr.innerHTML = "Age should be a number";
theAge.select();
} else if (theAge.value < 3 || theAge.value > 120) {
ageErr.innerHTML = "Please enter your real Age";
theAge.select();
return false;
} else{
ageErr.innerHTML = "";
}
for(var i=0; i < theRadioGp.length; i++) {
if(theRadioGp[i].checked ==true) {
chkValue = theRadioGp[i].value;
}
}
if(chkValue == undefined) {
alert('You need to slect a method of contact');
return false;
}
if(theSelect.options[theSelect.selectedIndex].text == "<--PLEASE SELECT ONE-->")
{alert("You need to select an option");
return false;
}else {
alert("Your have selected "+theSelect.options[theSelect.selectedIndex].text);
}
alert("Your form has been completed. Great Job!!");
}
</script>
</head>
<body>
<form action="" id="formContact" method="post" onsubmit="return validateForm();" name="formContact">
<p>Name:<br />
<input type="text" name="theName"><span class="err" id="nameErr"></span>
</p>
<p>Age:<br />
<input type="text" name="theAge"><span class="err" id="ageErr"></span>
</p>
<p>
<p>How may we contact you?<br>
<input type="radio" name="contact" value="email">Email<br>
<input type="radio" name="contact" value="no contact">No Contact<br>
</p>
<p>Please coose a selection below:<br>
<select name="theSelect">
<option><--PLEASE SELECT ONE -->
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>
<p><input type="submit" value="Submit" name="btnSubmit" ">
</form>
<span id="results"></span>
</body>
</html>

Your HTML isn't valid. Replace your select part with following
<select name="theSelect">
<option><--PLEASE SELECT ONE--></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Or use a numeric value for the default option
<select name="theSelect">
<option value="0">PLEASE SELECT AN OPTION</option>
<option value="1">One</option>
...
</select>
And check the value (not the text selected)
if(theSelect.options[theSelect.selectedIndex].value == 0){
alert("You need to select an option");
return false;
}else {
alert("Your have selected " + theSelect.options[theSelect.selectedIndex].text);
}

Why not use selectedIndex without the text?
Example:
<select id="mytest">
<option value="-1"><--PLEASE SELECT ONE--></option>
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
Then
if(theSelect.selectedIndex == -1)
{alert("You need to select an option");
return false;
}else {
the rest

Related

Why doesn't my function detect a correct input selection?

I need to write a JavaScript function that will check if correct answer is chosen in list and then will print either answer is right or not.
I came up with this -
HTML code:
<select id="q1" style="background-color: #b0f1f1">
<option value="1">Saulkrasti Beach</option>
<option value="2">Jurmala Beach</option>
<option value="3">Ventspils Beach</option>
</select>
<p id="answer"></p>
Javascript code:
function rightchoice()
{
var e = document.getElementById("q1");
var value = e.options[e.selectedIndex].value;
if (value == 2) {
document.getElementById("answer").innerHTML = "Right Answer";
}
}
But it does not print anything.
you should add an event onChange where you will call your function
const selection = document.getElementById("q1");
selection.addEventListener("change", rightchoice);
You can add an eventListener to your select listen for a change.
I have added here an else part to reset the value to an empty string when the wrong choice was selected.
function rightchoice()
{
var e = document.getElementById("q1");
var value = e.options[e.selectedIndex].value;
if (value == 2) {
document.getElementById("answer").innerHTML = "Right Answer";
}else{
document.getElementById("answer").innerHTML = "";
}
}
const fom = document.getElementById("q1");
fom.addEventListener("change", rightchoice);
<select id="q1" style="background-color: #b0f1f1">
<option value="1">Saulkrasti Beach</option>
<option value="2">Jurmala Beach</option>
<option value="3">Ventspils Beach</option>
</select>
<p id="answer"></p>
function rightchoice() {
var e = document.getElementById("q1");
var value = e.value;
if (value == 2) {
document.getElementById("answer").innerHTML = "Right Answer";
}
else{
document.getElementById("answer").innerHTML = "Wrong Answer";
}
}
<select id="q1" style="background-color: #b0f1f1" onchange="rightchoice()">
<option value="1">Saulkrasti Beach</option>
<option value="2">Jurmala Beach</option>
<option value="3">Ventspils Beach</option>
</select>
<p id="answer">This is answer</p>
document.getElementById('q1').addEventListener('change', function() {
var newVal = this.value;
if (newVal == 2) {
document.getElementById('answer').innerText = "Right answer.";
} else {
document.getElementById('answer').innerText = "Wrong answer.";
}
});
<select id="q1" style="background-color: #b0f1f1">
<option value="1">Saulkrasti Beach</option>
<option value="2">Jurmala Beach</option>
<option value="3">Ventspils Beach</option>
</select>
<p id="answer"></p>

Require the textarea to be filled in when certain option is selected

I need the textarea to be filled when "Other" is selected.
This is what I have, I thought it will work. But nothing shows up when other is selected and textarea is left blank.
html:
<form onsubmit="return validation()">
<span>Reason for inquiry: <span>
<select style="color:black" name="reasons">
<option value="catering">Catering</option>
<option value="private party">Private Party</option>
<option value="feedback">Feedback</option>
<option id="selectedOther" value="other">Other</option>
</select>
</form>
JS:
function validation(){
otherInquiry()
}
function otherInquiry(){
var x = document.getElementById("selectedOther").value;
if (document.getElementsByTagName("select") == x){
if(document.getElementById("txtArea").value == ""){
alert("Please tell us your reason of inquiry")
}
return false;
}
}

Get value of input inside an input

I have this form with the following options:
<select name="choices" id="options" onchange="showText()">
<option value="">Select amount</option>
<option value="1">100PHP</option>
<option value="2"> 500PHP</option>
<option value="3"> 1000PHP</option>
<option value="4"> 2000PHP</option>
<option value="5"> 3000PHP</option>
<option value="6"> 4000PHP</option>
<option value="7"> 5000PHP</option>
<option value="8"> 10,000PHP</option>
<option value="others"> others..</option>
</select>
<div class="control-group" id="show" style="display:none;">
When the user selects option 1-8, it will display the amount. I've successfully done that through this javascript:
function showText(){
var value = document.getElementById('options').value;
if(value == '1'){
var amount = document.getElementById("amount");
amount.value = "100";
document.getElementById('show').innerHTML =
"<br><br><font size =+1><b>Amount P 100 </b></font>"
document.getElementById('show').style.display = "block";
}
else if(value == '2'){
var amount = document.getElementById("amount");
amount.value = "500";
document.getElementById('show').innerHTML = "<br><br><font size =+1><b>Amount P 500 </b></font>"
document.getElementById('show').style.display = "block";
}
//up to option 8
Now, when the user selects 'others' it will display another input field. The value that the user will input will be the value option 'others':
else if (value == 'others'){
document.getElementById('show').innerHTML = "<br><div class='control-group'><label class='control-label'>Enter Amount</label><div class='controls'><input type='text' id='other_amount' name='other_amount'> ";
var amount = document.getElementById("other_amount").value;
document.getElementById('show').style.display = "block";
}
Unluckily, I was not successful in getting the value of the second input to be the value of the first input. I hope you could help! Thank you!
First of all, you can improve your code quite a lot:
function showText(){
var value = document.getElementById('options').value;
if(value == '-1'){
//Other
document.getElementById('hidden').style.display = 'block';
}
else {
document.getElementById('hidden').style.display = 'none';
var amount = document.getElementById("amount");
amount.value = value;
document.getElementById('show').innerHTML = "<br><br><font size =+1><b>Amount P " + value + "</b></font>"
document.getElementById('show').style.display = "block";
}
}
Where you change your html to:
<select name="choices" id="options" onchange="showText()">
<option value="">Select amount</option>
<option value="100">100PHP</option>
<option value="500">500PHP</option>
<option value="1000">1000PHP</option>
<!-- (...) -->
<option value="-1"> others..</option>
</select>
I'd also suggest adding the "hidden" input for when they choose others already in your html, but set it invisible:
<div id="hidden" style="display:none;"class='control-group'>
<label class='control-label'>Enter Amount</label><div class='controls'>
<input type='text' id='other_amount' name='other_amount' onChange='otherText()'/>
</div>
</div>
Now, when they select others.. with value -1 you want to show an input where they can choose their own value:
if (value == -1) {
document.getElementById('hidden').style.display = 'block';
}
Now we just need the function otherText() which shouldn't be a problem:
function otherText() {
document.getElementById('amount').value = document.getElementById("other_amount").value;
}
Working jsFiddle

How to check if an item is selected from an HTML drop down list?

I have a drop drown list and I am having trouble checking whether or not a value has been selected from the drop down list
Below is my HTML Code :
<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select><br/>
Below is my JavaScript Code :
var card = document.getElementByName("cards")[0].value;
if (card.value == selectcard) {
alert("Please select a card type");
}
Well you missed quotation mark around your string selectcard it should be "selectcard"
if (card.value == selectcard)
should be
if (card.value == "selectcard")
Here is complete code for that
function validate()
{
var ddl = document.getElementById("cardtype");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "selectcard")
{
alert("Please select a card type");
}
}
JS Fiddle Demo
<script>
var card = document.getElementById("cardtype");
if(card.selectedIndex == 0) {
alert('select one answer');
}
else {
var selectedText = card.options[card.selectedIndex].text;
alert(selectedText);
}
</script>
You can check if the index of the selected value is 0 or -1 using the selectedIndex property.
In your case 0 is also not a valid index value because its the "placeholder": <option value="selectcard">--- Please select ---</option>
LIVE DEMO
function Validate()
{
var combo = document.getElementById("cardtype");
if(combo.selectedIndex <=0)
{
alert("Please Select Valid Value");
}
}
function check(selId) {
var sel = document.getElementById(selId);
var dropDown_sel = sel.options[sel.selectedIndex].text;
if (dropDown_sel != "none") {
state=1;
//state is a Global variable initially it is set to 0
}
}
function checkstatevalue() {
if (state==1) {
return 1;
}
return false;
}
and html is for example
<form name="droptest" onSubmit="return checkstatevalue()">
<select id='Sel1' onchange='check("Sel1");'>
<option value='junaid'>Junaid</option>
<option value='none'>none</option>
<option value='ali'>Ali</option>
</select>
</form>
Now when submitting a form first check what is the value of state if it is 0 it means that no item has been selected.
<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard" selected="selected">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select><br />
<script>
var card = document.getElementById("cardtype");
if (card.options[card.selectedIndex].value == 'selectcard') {
alert("Please select a card type");
return false;
}
</script>
I believe this is the most simple in all aspects unless you call the validate function be other means. With no/null/empty value to your first option is easier to validate. You could also eliminate the first option and start with the most popular card type.
<form name="myForm">
<select id="cardtype" name="cards">
<option value="">--- Please select ---</option>
<option value="mastercard" selected="selected">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select><br />
<input type="submit" name="submit" class="button" value="SUBMIT" onmouseover="validate()"></form>
<script>
function validate() {
if (document.myform.cards.value == "") {
alert("Please select a card type");
document.myForm.cards.focus();
}
</script>
function checkSelected() {
if (optionsId.selectedIndex < 0) {
alert("Please select an item from options");
return false;
}}
Select select = new Select(_element);
List<WebElement> selectedOptions = select.getAllSelectedOptions();
if(selectedOptions.size() > 0){
return true;
}else{
return false;
}

validate forms with js

Hi I had my script working then I ran it through w3 validator and changed what I told me was wrong and now it stops validating at the first postcode, I have stuffed up and cant remember what was changed bigg lesson learnt do 1 thing at a time, I have been pulling my hair out trying to get it working again but cant figure out how if any 1 can take to time to look at it, I would greatly appreciate it, thanks
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Joes Fruit and Vegetable Store</title>
<script>
//calender dropdown menu
var monthtext = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
function populatedropdown(dayfield, monthfield, yearfield) {
var today = new Date()
var dayfield = document.getElementById(dayfield)
var monthfield = document.getElementById(monthfield)
var yearfield = document.getElementById(yearfield)
for (var i = 0; i < 31; i++)
dayfield.options[i] = new Option(i, i + 1)
dayfield.options[today.getDate()] = new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m = 0; m < 12; m++)
monthfield.options[m] = new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear = today.getFullYear()
for (var y = 0; y < 20; y++) {
yearfield.options[y] = new Option(thisyear, thisyear)
thisyear += 1
}
yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
// function validate
function validate_form() {
valid = true;
// validate name
/* if ( document.input.name.value == "" )
{
alert ( "Please enter your name" );
valid = false;
}
// validate address
if ( document.input.address.value == "" )
{
alert ( "Please enter your address address" );
valid = false;
}
// validate suburb town
if ( document.input.town.value == "" )
{
alert ( "Please enter your Suburb or town" );
valid = false;
}
// validate postcode
var y = document.getElementById("postcode").value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Postcode must be in numbers.");
document.getElementById("postcode").focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Postcode should be 4 digit");
document.getElementById("postcode").focus();
return false;
}
*/
// validate home phone
var y = document.getElementById('hphone').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("Home Phone number must be in numbers.");
document.getElementById('hphone').focus();
return false;
}
if (y.length > 10 || y.length < 10) {
alert("Home Phone number should be 10 digit");
document.getElementById('hphone').focus();
return false;
}
// validate work phone
var y = document.getElementById('wphone').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("work Phone number must be in numbers.");
document.getElementById('wphone').focus();
return false;
}
if (y.length > 10 || y.length < 10) {
alert("Work Phone number should be 10 digit");
document.getElementById('wphone').focus();
return false;
}
// validate fax
var y = document.getElementById('fax').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("Fax number must be in numbers.");
document.getElementById('fax').focus();
return false;
}
if (y.length > 10 || y.length < 10) {
alert("Fax Phone number should be 10 digit");
document.getElementById('fax').focus();
return false;
}
// validate email
{
var x = document.forms["input"]["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;
}
}
// validate radio buttons
var o = document.getElementById('rad1');
var t = document.getElementById('rad2');
if ((o.checked == false) && (t.checked == true)) {
// validate alternative address
if (document.input.street.value == "") {
alert("Please enter alternative address address");
valid = false;
}
// validate suburb town
if (document.input.suburb.value == "") {
alert("Please enter alternative Suburb or town");
valid = false;
}
} // validate postcode
var y = document.getElementById('postcode2').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("Postcode must be in numbers.");
document.getElementById('postcode2').focus();
return false;
}
if (y.length > 4 || y.length < 4) {
alert("Alternative Postcode should be 4 digit");
document.getElementById('postcode2').focus();
return false;
}
// validate message box
var o = document.getElementById('card');
if ((o.checked == true)) {
if (document.input.message.value == "") {
alert("Please enter message");
valid = false;
}
return valid;
}
}
</script>
</head>
<body> <b>Order form for Joe's Fruit Shop</B><br><br>
<b> * means you must fill in the details.</B><br><br>
<b>Your details:</b>
<br>
<br>
<!-- Beggining of Form -->
<form name="input" action="cal2.html" onsubmit="validate_form ()">
<!--name form -->* Name:
<input type="text" name="name" onclick="this.value='';" value="Enter your name with first">
<br>
<br>
<!-- Address form -->* Address:
<input type="text" name="address" onclick="this.value='';" value="Enter your street address">
<br>
<br>
<!-- Suburb state dropdown form-->* Suburb or Town:
<input type="text" name="town" onclick="this.value='';"
value="suburb">State:
<select name="state">
<option value="NSW">NSW</option>
<option selected="selected" value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
</select>
<!-- post code form -->* Postcode:
<input type=text name="postcode" onclick="this.value='';" value="****">
<br>
<br>
<!-- Home phone form-->* Phone:
<input type=text name="hphone" onclick="this.value='';" value="x-xxxx-xxx">
<!-- work phone form -->Work phone
<input type=text name="wphone" onclick="this.value='';" value="x-xxxx-xxx">
<br>
<br>
<!-- Fax form-->*Fax:
<input type=text name="fax" onclick="this.value='';" value="0x-xxxx-xxx">
<!-- Email form-->Email address:
<input type=text name="email" onclick="this.value='';" onsubmit="return validateForm();"
value="Enter your current email">
<br>
<br>
<br>
<!-- credit card--> <b>Credit card details:</b>
<br>
<br>* Type:
<select name="credit card">
<option selected="selected" value="AMEX">Amex</option>
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
</select>*Expiry date:
<select name="expiration_month">
<option value="">Choose...</option>
<option selected="selected" value="1">January</option>
<option value="2">Febuary</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="expiration_year">
<option value="">Choose...</option>
<option selected="selected" value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
<br>
<br>
<B>Purchase details</B><br><br> <!-- Product dropdown form-->
* Product:
<select name="product">
<option value="carrot">Bag of carrots</option>
<option value="zucchini">Zucchini</option>
<option value="cabbage">Cabbage</option>
<option value="grapes">Grapes</option>
<option value="tomatoes">TAS</option>
<option value="apples">Apples</option>
<option value="banana">banana</option>
<option selected="selected" value="cucumber">Cucumber</option>
</select>
<!-- Quantity dropdown form-->
Quantity:
<select name="quantity">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<br><br><br>
* <B>Deliver to:</B>
<br><br>
<!-- Address Radio buttons-->
<input type='radio' id="rad1" name='radio' value='Home address' checked="checked">Home Address<br>
<input type='radio' id="rad2" name='radio' value='Other address'/>Other Address<br><br>
<!--other address-->
<!-- street form-->
Street <input type=text name="street" onclick="this.value='';" value="Street"><br><br>
<!-- Suburb form-->
Suburb <input type=text name="suburb" onclick="this.value='';" value="Suburb or town"><br><br>
<!-- State dropdown form-->
State <select name="state">
<option value="NSW">NSW</option>
<option selected="selected" value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
</select><br><br>
<!-- post code form -->
Postcode:<input type=text name="postcode2" onclick="this.value='';" value="****"><br><br><br>
* Date delivery required:
<!-- Calender drop down menu-->
<select id="daydropdown">
</select>
<select id="monthdropdown">
</select>
<select id="yeardropdown">
</select>
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
}
</script>
<br><br>
<!-- include a card option-->
Include a card: <input type="checkbox" name="card" value="Yes">Yes<br><br>
Personal message on card: <textarea rows="10" name="message" cols="30" onclick="this.value='';" >Enter your personal message here</textarea><br><br>
Click on <b>Submit</b> when done; click on <b> Clear form</b> to reset.
<!-- submit button-->
<input type="submit" value="Submit">
<!-- reset button-->
<input type="reset" value="Reset">
</form>
</body>
</html>
Your scripts are failing as you are trying to get elements by Id and checking the value property of a null.
var y = document.getElementById('hphone').value;
This throws an exception and exits, the form then submits
Give your elements Ids to match the name attribute and it should be okay
<input type=text name="hphone" id="hphone" onclick="this.value='';" value="x-xxxx-xxx">
change your onsubmit attribute to the follow to cancel the submit on validation error
<form name="input" action="cal2.html" onsubmit="return validate_form ()">
To check against a default value, you could added a data attribute and cross check the value in the validation.
* Phone: <input type=text name="hphone" id="hphone" onclick="this.value='';" data-default="x-xxxx-xxx" value="x-xxxx-xxx">
var element = document.getElementById('hphone');
var y = element.value;
var defValue = element.attributes["data-default"].value;
if(isNaN(y)||y.indexOf(" ")!=-1|| y === defValue )
{
alert("Home Phone number must be in numbers.");
document.getElementById('hphone').focus();
return false;
}
If you are targetting HTML5 compliant browsers you could use the placeholder attribute.
http://www.w3schools.com/html5/att_input_placeholder.asp

Categories

Resources