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>
Related
I have two different select elements. One where a user select their gender and the second where a user selects a place they live.
I have;
<select class="selectGender" name="gender" id="styleSelect" required>
<option value="">None</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
and
<select class="selectPlace" name="place" id="styleSelect" onchange="return checkGender()" required>
<option name="dorm" value="">None</option>
<option name="dorm" value="town" name="">Town</option>
<option name="g" value="city">City</option>
</select>
What I want is that when a user selects male as gender and selects town from other select element, he should get an alert "not allowed".
Here's what I have done so far but I get nothing from this.
function checkGender() {
let gender = document.getElementsByName('gender');
let place = document.getElementsByName('place');
if (gender.value == "male" && place.value == "town") {
alert("Not allowed");
}
}
You have error on your html code check this
enter code here
<select class="selectGender" name="gender" id="styleSelect" required >
<option value="">None</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
enter code here
<select class="selectPlace" name="place" id="styleSelect1" onchange="checkGender()" required>
<option name="dorm" value="">None</option>
<option name="dorm" value="town">Town</option>
<option name="g" value="city">City</option>
</select>
<script>
function checkGender(){
let gender=document.getElementsByName('gender')[0].value;
let place=document.getElementsByName('place')[0].value;
console.log(gender);
console.log(place);
if (gender=="male"&&place=="town") {
alert("Not allowed");
}
}
</script>
Couple of errors with your code:
You can't have two or more elements with the same id but both of your selects have id="styleSelect".
You should add the checkGender() function to your first select too, as users not necessarily choose the second select last. Changing the first select should also fire the handler to check the values of the options.
As others have mentioned, getElementsByName returns a NodeList collection of elements with the given name. It means, you need to grab the element at the zeroth index.
You can check the working code below by clicking on the "Run code snippet" button:
function checkGender() {
let gender = document.getElementsByName('gender')[0];
let place = document.getElementsByName('place')[0];
if (gender.value === "male" && place.value === "town") {
alert("Not allowed");
}
}
<select name="gender" onchange="checkGender()" required>
<option value="">None</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<select name="place" onchange="checkGender()" required>
<option value="">None</option>
<option value="town">Town</option>
<option value="city">City</option>
</select>
Try
document.getElementsByName('gender')[0].value
<select id="test_me" name="test_me" disabled>
<option value="">Please select</option>
<option value="1">Test One</option>
<option value="2" selected>Test Two</option>
<option value="3">Test Three</option>
</select>
<input type="hidden" value="" name="test_hidden" id="test_hidden">
Here option Test Two is selected and disabled. The below code fetches select value when dropdown is enabled and value is changed.
//pass value to hidden input
$('#test_me').change(function () {
var id = $(this).val();
$('input#test_hidden').val(id);
})
How can I pass selected option value i.e. 2 to my hidden input, when dropdown is disabled and value is selected ?
This issue is reported at http://bugs.jquery.com/ticket/13097 and marked as wont fix. for reason:
The long-standing logic in .val() ensures that we don't return disabled options in a select-multiple. The change just applies the same behavior for select-one now for consistency.
Alternative for this would be to use selectedindex property of select to target option by index:
$("#test_me option").eq($("#test_me").prop("selectedIndex")).val();
Complete Snippet:
var id = $("#test_me option").eq($("#test_me").prop("selectedIndex")).val();;
$('input#test_hidden').val(id);
<script type="text/javascript">
//pass value to hidden input
$(document).ready(function(e) {
var sel = $("#test_me").val();
$("#test_hidden").val(sel);
});
</script>
<select id="test_me" name="test_me" disabled>
<option value="">Please select</option>
<option value="1">Test One</option>
<option value="2" selected>Test Two</option>
<option value="3">Test Three</option>
</select>
<input type="hidden" value="" name="test_hidden" id="test_hidden">
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;
}
}
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 :)