Validate country calling from API - javascript

<div class='input1'>
<select name="gender" class="gender" id="gender">
<option value="">Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
js
reg_gender = /(male|female)/;
if(form.gender.value == "" && (!reg_gender.test(form.gender.value)) ) {
alert("Please select gender!");
form.gender.focus();
return false;
}
EDITTED
How should I validate country using the method similar to gender? However, my country is not hardcoded. It is calling from an api.

Make simple change to your HTML:
<div class='input1'>
<select id="gender" name="gender" class="gender">
<option value="">Gender</option> <!-- make change value="" -->
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
Also add some line of codes in your javascript:
reg_gender = /(male|female)/;
if(form.gender.value == "" && (!reg_gender.test(form.gender.value)) ) {
alert("Please select gender!");
form.gender.focus();
return false;
}
This expression /(male|female)/ check if value is either male or female

Related

How to get values of two different select elements and use them in a function

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

Function to check option list validation not working

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>

Autoselect HTML hidden option value based on previous option

I have 2 select tags which come with the same option, male and female. One of the select, "age" is hidden.
<select name="gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<select name="age" style="display:none;">
<option value="12">Male</option>
<option value="18">Female</option>
</select>
When user select "male" in "gender", I wish the "age" will automatically select "male" as well. I expect the same thing as "female". How to achieve this through javascript?
You can attach an event change to your select gender and set the value of age on every change.
Note that both elements should be loaded with a default selected value for case that the end user do not select nothing and also check that it is better to move inline styling style="display:none;" to a separated css file.
Code:
var gender = document.getElementsByName('gender')[0],
age = document.getElementsByName('age')[0];
gender.addEventListener('change', function() {
age.value = (gender.value == 1) ? 12 : 18;
console.log('Gender:', gender.value);
console.log('Age:', age.value);
});
<select name="gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<select name="age" style="display:none;">
<option value="12">Male</option>
<option value="18">Female</option>
</select>
Here's an option using jQuery.
$(document).ready(function() {
$("#age").val("12");
$("#gender").change(function() {
var userselected = $(this).find(':selected').text();
if (userselected == "Male") {
$("#age").val("12");
} else {
$("#age").val("18");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="gender" id="gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<select name="age" style="display:inherit;" id="age">
<option value="12">Male</option>
<option value="18">Female</option>
</select>

Validating a select box

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;
}
}

How to apply validation to duplicate dropdown

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/

Categories