I was wondering how I go about validating that a user picked a country from the select box that I have coded.
The code:
<label>Select a Country:
<br />
<select name="country">
<option selected disabled>Choose a Country</option>
<option value="United States">United States</option>
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
</select>
</label>
Would the function look anything like:
function validateCountry(){
if (form.country.value=="")
alert("Please Select a Country!");
form.country.focus();
return false;
}
Your <select> element will currently have a default value of "Choose a Country" so your if statement will never be true (there is no option with a value == ''). Set the value attribute to change that.
form isn't defined. You can select your form with a variety of methods, one option being document.querySelector(). The following assumes that the subject <select> box is the first matching select[name="country"] in your document.
function validateCountry(){
var selectBox = document.querySelector('select[name="country"]');
if (selectBox.value==""){
alert("Please Select a Country!");
selectBox.focus();
return false;
}
}
document.getElementById('button').onclick = validateCountry;
<label>Select a Country:
<br />
<select name="country">
<option value='' selected disabled>Choose a Country</option>
<option value="United States">United States</option>
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
</select>
</label>
<button id='button'>Validate</button>
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
Can Also Validate based on document.getElementById, just add the code, id="country" in select box,
<label>Select a Country:
<br />
<select name="country" id="country">
<option value="">Choose a Country</option>
<option value="United States">United States</option>
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
</select>
</label>
<button id='submit' onclick="return validateCountry();">Validate</button>
function validateCountry() {
if(document.getElementById('country').value =='')
{
alert("Please select a country");
return false;
}
else
{
return true;
}
}
Related
I have a select option list for my form and I want to make sure the user has selected one of the options. My function logic implies that if the user keeps the dropdown on the default option, an alert will pop up prompting them to change it. However, no alert shows up whatsoever. What am I doing wrong?
function isOption(form) {
var type = form.getElementByID("pastimetype")
var selectedValue = type.options[type.selectedIndex].value;
if (selectedValue == "selectpastime") {
alert("Please select a pastime.")
return false
}
return true
}
<p><label for="pastime"> Favourite pastime: </label>
<select name="pastime" select id="pastimetype">
<option value="selectpastime">---Please choose an option---</option>
<option value="surfingtheweb">Surfing the Web</option>
<option value="playingsport">Playing Sport</option>
<option value="listeningtomusic">Listening to Music</option>
<option value="watchingtv">Watching TV</option>
<option value="playinggames">Playing Games</option>
<option value="communityservice">Community Service</option>
<option value="daydreaming">Daydreaming</option>
<option value="reading">Reading</option>
<option value="meditation">Meditation</option>
</select>
</p>
you need to add the function to the submit event of the form.
you misspelled getElementById
no need to use form.getElementById
easier to get the value using select.value
use preventDefault instead of returning true/false
Also
function isOption(e) {
var sel = document.getElementById("pastimetype");
var selectedValue = sel.value;
if (selectedValue == "") { // I removed the value from the "Please select"
alert("Please select a pastime.")
e.preventDefault(); // stop submission
}
}
window.addEventListener("load",function() {
document.getElementById("form1").addEventListener("submit",isOption)
})
<form id="form1">
<p><label for="pastime"> Favourite pastime: </label>
<select name="pastime" select id="pastimetype">
<option value="">---Please choose an option---</option>
<option value="surfingtheweb">Surfing the Web</option>
<option value="playingsport">Playing Sport</option>
<option value="listeningtomusic">Listening to Music</option>
<option value="watchingtv">Watching TV</option>
<option value="playinggames">Playing Games</option>
<option value="communityservice">Community Service</option>
<option value="daydreaming">Daydreaming</option>
<option value="reading">Reading</option>
<option value="meditation">Meditation</option>
</select>
</p>
<input type="submit" />
</form>
I want to show another dropdown list beneath the current one once the user chooses Rank or Department. After choosing from the new list, they user can submit the form.
Similarly, if the user chooses any other option (except LastName), a textbox will appear that needs to be filled in before they can click the submit button.
<form action="viewEmployeeHTML.php" method="post">
<div class="outer-div">
<div class="inner-div">
<br><br><br>
<h2>Search By:</h2>
<select name="selectionToView" class="SelectBox">
<option value="Select">-- Select --</option>
<option value="ID">ID</option>
<option value="FirstName">First Name</option>
<option value="MiddleName">Middle Name</option>
<option value="LastName">Last Name</option>
<option value="Email">Email</option>
<option value="Phone">Phone</option>
<option value="IP_Phone">IP Phone</option>
<option value="OfficeNumber">Office Number</option>
<option value="CoordinatorName">Coordinator Name</option>
<option value="Rank">Rank</option>
<option value="Department">Department</option>
<option value="JoiningDate"> Joining Date</option>
<option value="Committee_AND_Unit">Committee/Unit</option>
</select><br><br><br>
</div>
</div>
<br><br><br>
<center><input type="submit" value="VIEW" name="view"></center>
</form>
I tried this code but it didn't work for me:
<form action="viewEmployeeHTML.php" method="post">
<div class="outer-div" >
<div class="inner-div">
<br><br><br>
<h2>Search By:</h2>
<select name="selectionToView" class="SelectBox" onchange="OnSelectionChange()">
<option value="Select">-- Select --</option>
<option value="ID">ID</option>
<option value="FirstName">First Name</option>
<option value="MiddleName">Middle Name</option>
<option value="LastName">Last Name</option>
<option value="Email">Email</option>
<option value="Phone">Phone</option>
<option value="IP_Phone">IP Phone</option>
<option value="OfficeNumber">Office Number</option>
<option value="CoordinatorName">Coordinator Name</option>
<option value="Rank">Rank</option>
<option value="Department">Department</option>
<option value="JoiningDate"> Joining Date</option>
<option value="Committee_AND_Unit">Committee/Unit</option>
</select>
<br><br><br>
</div>
</div>
<br><br><br>
<center><input type="submit" value="VIEW" name="view"></center>
</form>
<script>
function OnSelectionChange(){
</script>
<?php
$selectionToView=$_POST['selectionToView']
if(isset(selectionToView) == "ID"){
?>
<script>document.write("<center><input type="submit" value="VIEW" name="view"></center>");</script>
<?php
}
?>
<script>
}
</script>
I've sligthly changed the HTML and wrote JavaScript for it with a little help of CSS.
function OnSelectionChange(value) {
document.getElementById("submit-button").disabled = true;
if ( value == "Rank" ) {
document.getElementById("rank-select").style.display = "block";
document.getElementById("department-select").style.display = "none";
document.getElementById("text").style.display = "none";
} else if ( value == "Department" ) {
document.getElementById("rank-select").style.display = "none";
document.getElementById("department-select").style.display = "block";
document.getElementById("text").style.display = "none";
} else if ( value == "Select" ) {
document.getElementById("rank-select").style.display = "none";
document.getElementById("department-select").style.display = "none";
document.getElementById("text").style.display = "none";
} else {
document.getElementById("rank-select").style.display = "none";
document.getElementById("department-select").style.display = "none";
document.getElementById("text").style.display = "block";
}
}
function onSecondSelectChange(value) {
if ( value != "Select" ) {
document.getElementById("submit-button").disabled = false;
} else {
document.getElementById("submit-button").disabled = true;
}
}
function onTextChange(value) {
if ( value != "" ) {
document.getElementById("submit-button").disabled = false;
} else {
document.getElementById("submit-button").disabled = true;
}
}
#rank-select,
#department-select,
#text {
display: none;
}
<form>
<div class="outer-div" >
<div class="inner-div">
<h2>Search By:</h2>
<select name="selectionToView" class="SelectBox" onchange="OnSelectionChange(this.options[this.selectedIndex].value)">
<option value="Select">-- Select --</option>
<option value="ID">ID</option>
<option value="FirstName">First Name</option>
<option value="MiddleName">Middle Name</option>
<option value="LastName">Last Name</option>
<option value="Email">Email</option>
<option value="Phone">Phone</option>
<option value="IP_Phone">IP Phone</option>
<option value="OfficeNumber">Office Number</option>
<option value="CoordinatorName">Coordinator Name</option>
<option value="Rank">Rank</option>
<option value="Department">Department</option>
<option value="JoiningDate"> Joining Date</option>
<option value="Committee_AND_Unit">Committee/Unit</option>
</select>
<select name="rank-select" id="rank-select" onchange="onSecondSelectChange(this.options[this.selectedIndex].value)">
<option value="Select">-- Select --</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="department-select" id="department-select" onchange="onSecondSelectChange(this.options[this.selectedIndex].value)">
<option value="Select">-- Select --</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="text" name="text" id="text" onchange="onTextChange(this.value)">
</div>
</div>
<input type="submit" value="VIEW" name="view" id="submit-button" disabled="disabled">
</form>
If i understood you correctly, you want another select list or textarea to appear under the current select list when the user selects certain option. Select list when he picks Rand or Department, and textarea in all other cases.
What i would do is make those extra elements you need(another select list and textarea) and put them on display:none. Then with onchange event handler use a function that would check which option is selected and display/hide whatever you need. You would need an extra select list for each option in the first select list, but in case you are populationg option from a database, then you could use ajax to dinamicaly populate single select list depending on what the user picked.
Hope this helps.
onchange would be like:
onchange='displayList(this)'
function would look something like this:
function displayList(selectObject){
var option = selectObject.value;
if(option == 'Department' || option == 'Rank'){
document.getElementById('select').style.display='inline';
document.getElementById('text').style.display='none';
}
else{
document.getElementById('select').style.display='none';
document.getElementById('text').style.display='inline';
}
if(option == 'Select'){
document.getElementById('select').style.display='none';
document.getElementById('text').style.display='none';
}
}
This is working form with select, but how to make it work same but in form?
<select id="destination" name="destination" onchange="navigate(this.options[this.selectedIndex].value)">
<option value="">Select country</option>
<option value="afghanistan">Afghanistan</option>
<option value="albania">Albania</option>
<option value="algeria">Algeria</option>
<option value="andorra">Andorra</option>
<option value="angola">Angola</option>
Script.js
function navigate(destination)
{
if (destination != "")
location.href = destination + ".php";
}
It is there anyway make it work with "datalist"?
<datalist id="countries" >
<option value="Afghanistan">
<option value="Albania">
<option value="United Kingdom">
<option value="United States">
<option value="Vanuatu">
<option value="Vatican City">
<option value="Yemen">
<option value="Zambia">
<option value="Zimbabwe">
</datalist>
To get the form value in the onsubmit handler via JavaScript you can assign id to the input element, and then programatically read its value.
function myFunction() {
// 1. use the id 'txtCountry' to get reference to the INPUT element
// Note: you need to edit your HTML to assign the id 'txtCountry' (see sample HTML below)
var txtCountry = document.getElementById('txtCountry');
// 2. assign the value (text) in the INPUT element to a variable called 'destination'
var destination = txtCountry.value;
// 3. redirect to an URL based on the value from step 2
var url = destination + ".php";
alert("You are about to redirect to\n\n" + url);
location.href = url;
}
<form onsubmit="myFunction()">
Enter country:
<input type="text" id="txtCountry" name="txtCountry" list="countries">
<input type="submit" value="Submit">
</form>
<datalist id="countries">
<option value="Afghanistan">
<option value="Albania">
<option value="United Kingdom">
<option value="United States">
<option value="Vanuatu">
<option value="Vatican City">
<option value="Yemen">
<option value="Zambia">
<option value="Zimbabwe">
</datalist>
I have drop-down box in loop. so I want to apply validation.
My Code is-
<select name="travelclasscmb[]" id="travelclasscmb">
<option value="">select</option>
<option value="1">Car</option>
</select>
<select name="travelclasscmb[]" id="travelclasscmb">
<option value="">select</option>
<option value="2">Train</option>
</select>
Try
$('select ').change(function () {
if (this.value === '') {
alert('select a value');
}
});
ID must be unique use classes instead .
Read Two HTML elements with same id attribute: How bad is it really?
Using jQuery Validator
$.validator.addMethod('notNone', function (value, element) {
return (value !== '');
}, 'Please select an option');
To start off, you can't have duplicate id's. Use a class instead.
For the validation you can use the required attribute:
<select name="travelclasscmb[]" class="travelclasscmb" required>
<option value="">select</option>
<option value="1">Car</option>
</select>
<select name="travelclasscmb[]" class="travelclasscmb" required>
<option value="">select</option>
<option value="2">Train</option>
</select>
Please use class for multiple select validation
<select name="travelclasscmb[]" class="travelclasscmb" required>
<option value="">select</option>
<option value="1">Car</option>
</select>
<select name="travelclasscmb[]" class="travelclasscmb" required>
<option value="">select</option>
<option value="2">Train</option>
</select>
**Jquery:**
$('.travelclasscmb').change(function () {
if (this.value === '') {
alert('select a value');
}
});
demo http://jsfiddle.net/kapil_dev/mdBtz/
How Can i specific require and unique condition for a list of select box like below?
<form name="signupForm" class="cmxform" id="signupForm" method="get" action="">
<select name="category[]" id="cat_1">
<option value="">Select One</option>
<option value="1">aa</option>
<option value="2">bb</option>
<option value="3">cc</option>
<option value="4">dd</option>
</select>
<select name="category[]" id="cat_2">
<option value="">Select One</option>
<option value="5">ee</option>
<option value="6">ff</option>
<option value="7">gg</option>
<option value="8">hh</option>
</select>
<select name="category[]" id="cat_3">
<option value="">Select One</option>
<option value="9">ii</option>
<option value="10">jj</option>
<option value="11">kk</option>
<option value="12">ll</option>
</select>
<input class="submit" type="submit" value="Submit">
</form>
Notice that there are the number of cat is not fixed, it can be more than 3,
so how to make it required for each selectbox,
and each selectbox chosen value must be unique using jquery validate plugin? Thank you
var $selects = $('form select[name^=category]'),
values = [];
$(':submit').click(function(e) {
e.preventDefault();
values = [];
$($selects).each(function() {
if($(this).val()) {
values.push($(this).val());
}
});
if(!values.length) {
alert('Please select all categories');
return false;
}
if(values.length < $selects.length || $.unique(values).length < $selects.length) {
alert('Please select all categories and be unique');
return false;
}
});
DEMO
Here is a great jQuery validation plugin that will make your life easier: http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
This is all you need to do: (the plugin does the rest)
<select id="sport" class="validate[required]" name="sport">
<option value="">--Select--</option>
<option value="option1">Tennis</option>
<option value="option2">Football</option>
<option value="option3">Golf</option>
</select>
Hope that helps :)