validation for select option not working - javascript

I doing a form for a small project, and having a trouble trying to validate the select option
hope someone can help
THanks in advance
HTML:
<form method="post" name="vehicleform" action=" " onSubmit="return (validateForm())">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
Phone Number <font size="1px">(ex. 123-456-7890)</font>: <input type="text" name="phonenumber"><br>
Location
<select name="location">
<option value="-1">Select one..</option>
<option value="lota">Lot A</option>
<option value="lotb">Lot B</option>
<option value="lotc">Lot C</option>
</select><br>
JS:
function validateForm(){
var d = document.forms['vehicleform']['location'].value;
if( document.vehicleform.location.value == "-1" )
{
alert("Please select your location");
return false;
}
}

There is no need for grouping in the listener, and passing this gives immediate access to the form:
<form ... onsubmit="return validateForm(this)">
You only need to check the selected index to see if something other than the first option (or no option all) is selected:
function validateForm(form) {
if (form.location.selectedIndex < 1) {
alert("Please select your location");
return false;
}
}
And as suggested in the comments, make the first option selected by default:
<select name="location">
<option value="-1" selected>Select one..
<option value="lota">Lot A
as browsers may not make any option selected by default and users won't see "Select one...". That should be a label anyway to assist with accessiblity.

http://jsfiddle.net/LVBSZ/1/
You have no submit button in your code and close tag for form. The other works for me
<script>
function validateForm() {
if (document.forms['vehicleform'].location.value == "-1") {
alert("Please select your location");
return false;
}
}
</script>
<form method="post" name="vehicleform" onSubmit="return validateForm()">
First Name:
<input type="text" name="fname">
<br>Last Name:
<input type="text" name="lname">
<br>Phone Number <font size="1px">(ex. 123-456-7890)</font>:
<input type="text" name="phonenumber">
<br>Location
<select name="location">
<option value="-1">Select one..</option>
<option value="lota">Lot A</option>
<option value="lotb">Lot B</option>
<option value="lotc">Lot C</option>
</select>
<br>
<input type="submit" value="Submit">
</form>

Related

Change form action based on form select field

I can't get the form action to change based on a user's drop-down selection. What I want to do is have the form redirect to a different page, then the default for the form if a user selects "Student Loans" from the select field named "agency".
In other words, what I want to do is that if someone select "student loans" for the agency, I want the page to submit to /quote/quotes-sl.php instead of quote/quotes.php (the default of the form).
Here is my form code:
<form id="tdhcustom-pre-1-form" accept-charset="UTF-8" onsubmit="submit_function(this)" action="/quote/quotes.php" method="post" name="tdhcustom-pre-1-form">
<input id="edit-lead-source-description" name="lead_source_description" type="hidden" value="test" />
<label class="edit-owed" for="edit-owed"> Amount Owed: <span class="form-required" title="This field is required.">*</span>
</label><select id="owed" class="form-select required" name="owed">
<option selected="selected" value="">Select...</option>
<option value="$10,000 to $14,999">$10,000 to $14,999</option>
<option value="$15,000+">$15,000+</option>
</select>
<label class="edit-agency" for="edit-agency"> Problem With: <span class="form-required" title="This field is required.">*</span>
</label><select id="agency" class="form-select required" name="agency">
<option selected="selected" value="">Select Agency...</option>
<option value="Student Loan" data-action="/quote/quotes-sl.php">Student Loan</option>
<option value="FEDERAL">Federal Taxes</option>
<option value="STATE">State Taxes</option>
</select></div>
<input id="edit-submit" class="form-submit" height="31" name="submit" src="test.com/test.jpg" type="image" value="Submit" width="214" />
<input id="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" name="form_build_id" type="hidden" value="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" />
<input id="edit-tdhcustom-pre-1-form" name="form_id" type="hidden" value="tdhcustom_pre_1_form" />
</form>
Here is the javascript:
<script>
function submit_function(form) {
var selected = document.getElementById('Agency');
var dataset = selected[selected.selectedIndex].dataset;
if (dataset.action) {
form.action = dataset.action;
}
return true;
};
</script>
Add trigger on selected option val = "Student Loan" , then change attribute "action" form to url "/quote/quotes-sl.php"
$('#agency').on('change',function(){
var selected = $(this).val();
if(selected == "Student Loan")
$('#tdhcustom-pre-1-form').prop('action',"/quote/quotes-sl.php");
});
CMIIW :D
You want to change the form action based on an onchange event from your <select> ... but you'll also want to remove the onsubmit attribute from your form, like so:
<form id="tdhcustom-pre-1-form" accept-charset="UTF-8" action="/quote/quotes.php" method="post" name="tdhcustom-pre-1-form">
Assuming you're going to have data attributes on all the options like this:
<select id="agency" class="form-select required" name="agency">
<option selected="selected" value="">Select Agency...</option>
<option value="Student Loan" data-action="/quote/quotes-sl.php">Student Loan</option>
<option value="FEDERAL" data-action="/quote/quotes-s2.php">Federal Taxes</option>
<option value="STATE" data-action="/quote/quotes-s3.php">State Taxes</option>
</select>
You can just replace your <script> block with:
<script>
(function() {
var theForm = document.getElementById('tdhcustom-pre-1-form');
var theSelector = document.getElementById('agency');
theSelector.onchange = function() {
theForm.action = theSelector[theSelector.selectedIndex].getAttribute('data-action');
}
})();
</script>
That's pure JavaScript - so without jQuery (or any other framework).

Validate select dropdown with javascript

I'm having trouble with validating my dropdown list with javascript. What I want is to display an error message underneath the field inside span tags if the user hasn't selected any options. I've checked almost every tutorials out there but no luck.
Here is the code for the form:
<form name="subform" id="subform" action="submit.php" onsubmit="return checkForBlank()" method="POST" enctype="multipart/form-data">
<div class="md-form">
<input type="text" id="subcim" name="subcim" class="form-control"><span class="error_form" id="subcim_error_message"></span>
<label for="subcim" class="">Title</label><br>
</div>
<div class="md-form">
<select class="mdb-select" id="subcat" name="subcat"><span class="error_form" id="subcat_error_message"></span>
<option value="0" selected>Please select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<label id="subcat_info">Category</label><br>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Submit</button>
</form>
and here is the Javascript code (the first if statement validates the input field in the form:
function checkForBlank() {
if(document.getElementById("subcim").value == "") {
document.getElementById("subcim_error_message").textContent="You must add a title!";
return false;
} else if(document.getElementById("subcim").value.length < 5 || document.getElementById("subcim").value.length > 80) {
document.getElementById("subcim_error_message").textContent="The title must be between 5 and 80 characters!";
return false;
}
var result = document.getElementById('subcat').value;
if (result === "0") {
document.getElementById("subcat_error_message").textContent="You must select an option!";
return false;
}
}
I'm using
onsubmit="return checkForBlank()"
inside the form tag.
When I submit the form without selecting an option, the form seems to be submitted properly, but it does not display the error message.
Any help is appreciated
function Validate() {
var subcat= document.getElementById("subcat");
if (subcat.value == "") {
//If the "Please Select" option is selected display error.
alert("Please select an option!");
return false;
}
return true;
}
onsubmit ="return Validate()"
function Validate() {
var subcat= document.getElementById("subcat");
if (subcat.value == "0") {
//If the "Please Select" option is selected display error.
alert("Please select an option!");
return false;
}
return true;
}
onsubmit ="return Validate();"
Change your syntex from
<div class="md-form">
<select class="mdb-select" id="subcat" name="subcat"><span class="error_form" id="subcat_error_message"></span>
<option value="0" selected>Please select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<label id="subcat_info">Category</label><br>
</div>
To syntex as below
<div class="md-form">
<select class="mdb-select" id="subcat" name="subcat">
<option value="0" selected>Please select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<span class="error_form" id="subcat_error_message"></span>
<label id="subcat_info">Category</label><br>
</div>
The only mistake that you are doing is putting your error span within your select tag it self which is not a predefined HTML format for select tag. As you can see that after putting your span tag out side your select tag every thing will work as you want.
Html
<div class="md-form">
<select class="mdb-select" id="subcat" name="subcat">
<option value="0" selected>Please select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<span class="error_form" id="subcat_error_message"></span>
<label id="subcat_info">Category</label><br>
</div>
JavaScript
function Validate() {
var subcat= document.getElementById("subcat");
if (subcat.value == "0") {
//If the "Please Select" option is selected display error.
document.getElementById("subcat_error_message").innerHTML="Error Message";
//OR
document.getElementById("subcat_error_message").textContent="Error Message";
return false;
}
return true;
}
onsubmit ="return Validate();"

how do I alert user when they didn't select an option on a drop-down menu

I made a drop-down menu for user to select,for the date, it looks like this
How do I the alert user that they didn't select a date? The month, day and year are options in the <select> element
if(document.forms[0].checkindate.selectedIndex == 1) {
window.alert("You must select a date.");
return false;
}
I did this, but it doesn't work.
Give select values are empty and validate by using html required like
<select required>
<option value="">Month</option>
<option vslue="1">1</option>
</select>
<select required>
<option value="">Day</option>
<option vslue="1">1</option>
</select>
<select required>
<option value="">Year</option>
<option vslue="2016">2016</option>
</select>
Or use Javascript or jQuery Validation
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function validate()
{
if(document.getElementById("city").value=="-1")
{
alert('Please select a city');
return false;
}
else if (document.getElementById('day').value=='')
{
alert('Please provide date for D.O.B');
document.getElementById("day").style.borderColor="red";
document.getElementById("day").style.backgroundColor="yellow";
document.getElementById("day").style.borderWidth=2;
return false;
}
else if (document.getElementById('month').value=='')
{
alert('Please provide month for D.O.B');
document.getElementById("month").style.borderColor="red";
document.getElementById("month").style.backgroundColor="yellow";
document.getElementById("month").style.borderWidth=2;
return false;
}
else if (document.getElementById('year').value=='')
{
alert('Please provide year for D.O.B');
document.getElementById("year").style.borderColor="red";
document.getElementById("year").style.backgroundColor="yellow";
document.getElementById("year").style.borderWidth=2;
return false;
}
}
</script>
<body>
<form >
City : <select id="city">
<option value="-1">-~Select One~-</option>
<option>City 1</option>
<option>City 2</option>
<option>City 3</option>
<option>City 4</option>
<option>City 5</option>
</select>
<br>
Date of Birth:
Day
<input type="number" name="day" id='day' min="1" max="31" value="" required>
Month
<input type="number" name="month" min="1" id='month' max="12" value="" required>
Year
<input type="number" name="year" min="1950" id='year' max="2020" value="" required>
<input type="submit" value="Login" onclick="return(validate());"
</form>
</body>
</html>
Refer to the above given example to have a clear view. Hope you will understand.
You can use the .each() function to check if any of the dropdowns are not selected by the user.
$('select').each(function () {
if (this.value)
alert('value selected');
else
alert('no selection');
});

How to validate that the user selected in select form

I have select form:
<form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt">
<select style="background: transparent; border-bottom:5px;" name="subname" class="required">
<option value="" > Choose subject </option>
<option value="aaa" > AAA </option>
<option value="bbb" > BBB </option>
</select>
<input type="submit" value="post" name="txt" class="btn" id="post_button" onClick="time_get()">
</form>
I want to put alert label if the user pressed "post", but didn't choose a subject
Edit- thanks to maihan's answer I could fix it:
function time_get()
{
var selected = document.getElementById("select_post_id");
var selectedVal = selected.options[selected.selectedIndex].value;
if(selectedVal != ""){
//do whatever
}else{alert('select an option');}
}
Place the logic in time_get() function you have.
if(document.getElementsByTagName(select).value ==''){
alert("Select an option")
}
You can add an event handler on the form to prevent submitting it if the select has no value, then show an alert or add/unhide a warning <label>.
$('form#post_txt').submit(function(event){
var subname = $('select[name="subname"]').val()
if(subname === null || subname === "") {
event.preventDefault();
//warn user
}
});
I would also recommend adding selected="selected" as an attribute on your first select option, so that it will be selected from the start, instead of a blank select.
Maihan's answer is great, but just to improve, I would make the value of 'Choose Subject', 'NULL' and then validate using the if statement
<form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt">
<select style="background: transparent; border-bottom:5px;" name="subname" class="required">
<option value=NULL > Choose subject </option>
<option value="aaa" > AAA </option>
<option value="bbb" > BBB </option>
</select>
<input type="submit" value="post" name="txt" class="btn" id="post_button" onClick="time_get()">
Then... js...
function time_get(){
if(document.getElementByClassName(required) != NULL){
//do whatever
}else{alert('select an option')}
}

Form validation (radio & combobox) in javascript

I am trying to validate radiobuttons and optionbox in javascript. Here is the code but it is not working...
Javascript Code for OprionBox and Radio:
function checkCountry()
{
if(document.form.country.selectedIndex=="")
{
alert("Please select country from the list");
return false;
}
return true
}
function checkGender()
{
if(!document.getElementsByName("sex")[0].checked && !document.getElementsByName("sex")[1].checked)
{
alert("Select Male/Female");
return false;
}
return true;
}
function validate()
{
checkCountry();
checkGender();
}
HTML code:
<form name="form" method="post" onSubmit="return validate()">
<select name="country">
<option value="select">(Please select a country)</option>
<option value="pk">Pakistan</option>
<option value="chn">China</option>
<option value="uk">United Kingdom</option>
<option value="usa">United States of America</option>
<option value="ir">Iran</option>
<option value="ma">Malaysia</option>
</select><br>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br></form>
Please help...
Change if(document.form.country.selectedIndex=="") to if(document.getElementsByName("country").selectedIndex=="0")
You'll have to change the line where you check for the selected index to:
if(document.form.country.selectedIndex === 0) thats because of your "Please select a country" entry you will always have a selected index.
If i then add <input type="submit" value="test"/> inside your form to test submitting i will get your error messages.
Please see http://jsbin.com/oviped/2/edit it is working!
This is whole code and its working fine
<html>
<head>
<script type="text/javascript">
function checkGender()
{
if(!document.getElementsByName("sex")[0].checked && !document.getElementsByName("sex")[1].checked)
{
alert("Select Male/Female");
return false;
}
return true;
}
function checkCountry()
{
if(document.getElementsByName("country")[0].selectedIndex==0)
{
alert("Please select country from the list");
return false;
}
return true
}
function validate()
{
checkCountry();
checkGender();
}
</script>
</head>
<body>
<form onSubmit="return validate()" >
<select name="country">
<option value="select">(Please select a country)</option>
<option value="pk">Pakistan</option>
<option value="chn">China</option>
<option value="uk">United Kingdom</option>
<option value="usa">United States of America</option>
<option value="ir">Iran</option>
<option value="ma">Malaysia</option>
</select><br>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
<input type="submit" value="Submit" >
</form>
</body>
</html>

Categories