good afternoon from Sweden!
I have a problem with a javascript code which gives me "NaN" while trying to get it to count my points from my grades. It should check which score it is and then take what it's worth and adding that to the final score which will be alerted when pressing the button.
Javascript:
var biobetyg;
var bildbetyg;
function bBio() {
var bio = document.getElementById("bio");
var biobe = bio.options[bio.selectedIndex].value;
if ((biobe === "-") || (biobe === "f")) {
biobetyg = 0;
} else if (biobe === "e") {
biobetyg = 10;
} else if (biobe === "d") {
biobetyg = 12.5;
} else if (biobe === "c") {
biobetyg = 15;
} else if (biobe === "b") {
biobetyg = 17.5;
} else if (biobe === "a") {
biobetyg = 20;
}
}
function bBild() {
var bild = document.getElementById("bild");
var bildbe = bild.options[bild.selectedIndex].value;
if ((bildbe === "-") || (bildbe === "f")) {
bildbetyg = 0;
} else if (bildbe === "e") {
bildbetyg = 10;
} else if (bildbe === "d") {
bildbetyg = 12.5;
} else if (bildbe === "c") {
bildbetyg = 15;
} else if (bildbe === "b") {
bildbetyg = 17.5;
} else if (bildbe === "a") {
bildbetyg = 20;
}
}
var merit = bildbetyg + biobetyg;
function GetSelectedItem() {
var strSel = "The Value is: " + merit + " and text is: ";
alert(strSel);
}
HTML:
<form>
<h1>Bild</h1>
<h2>Välj ditt betyg i bild:</h2>
<select id="bild" onchange="bBild()">
<option class="f" value="-">-</option>
<option class="f" value="f">F</option>
<option class="go" value="e" selected>E</option>
<option class="go" value="d">D</option>
<option class="go" value="c">C</option>
<option class="go" value="b">B</option>
<option class="go" value="a">A</option>
</select>
<select id="bio" onchange="bBio()">
<option class="f" value="-">-</option>
<option class="f" value="f">F</option>
<option class="go" value="e" selected>E</option>
<option class="go" value="d">D</option>
<option class="go" value="c">C</option>
<option class="go" value="b">B</option>
<option class="go" value="a">A</option>
</select>
<input type="button" value="Press to Confirm" onClick="GetSelectedItem();">
</form>
As Pointy pointed out, I suggest changing your html to:
<form>
<h1>Bild</h1>
<h2>Välj ditt betyg i bild:</h2>
<select id="bild" onchange="bBild()">
<option class="f" value="0">-</option>
<option class="f" value="0">F</option>
<option class="go" value="10" selected>E</option>
<option class="go" value="12.5">D</option>
<option class="go" value="15">C</option>
<option class="go" value="17.5">B</option>
<option class="go" value="20">A</option>
</select>
<select id="bio" onchange="bBio()">
<option class="f" value="0">-</option>
<option class="f" value="0">F</option>
<option class="go" value="10" selected>E</option>
<option class="go" value="12.5">D</option>
<option class="go" value="15">C</option>
<option class="go" value="17.5">B</option>
<option class="go" value="20">A</option>
</select>
<input type="button" value="Press to Confirm" onClick="GetSelectedItem();">
</form>
So you can avoid the need of the ifs (or even using switch() which would be a better option, and then you can change your JavaScript to (the parseFloat() parts are to avoid treating the values as strings, as that would only concatenate instead of adding up the numbers):
function bBio()
{
var bio = document.getElementById("bio");
var biobetyg = parseFloat(bio.options[bio.selectedIndex].value);
return biobetyg;
}
function bBild()
{
var bild = document.getElementById("bild");
var bildbetyg = parseFloat(bild.options[bild.selectedIndex].value);
return bildbetyg;
}
function GetSelectedItem()
{
var merit = bBio() + bBild();
var strSel = "The Value is: " + merit + " and text is: ";
alert(strSel);
}
This greatly reduces your JS code and I think it's more readable... (besides actually working
WORKING DEMO
The problem is that this line:
var merit = bildbetyg + biobetyg;
sets the variable "merit" before either of those two functions runs. It is not recomputed automatically just because the other two variables change.
Move that line of code inside the "GetSelectedItem" function and things should work much better.
You'll also need to initialize the two variables so that if the button is clicked before the values change, it still works. In fact you could have that "GetSelectedItem" function simply call the two functions itself before computing the sum.
Related
When someone clicks on the "Submit" button I would like it to call a function that is currently selected on the 'paymentMethod' option group box.
For example if I selected the Bitcoin option it will call the bitcoin() function and the button will look like this:
<button onclick='bitcoin()' class='btn btn-primary'>Submit</button>
My code:
<select class="form-control select2" id='paymentMethod'>
<optgroup label="Crypto">
<option value="Bitcoin">Bitcoin, Etherum, Litecoin, DogeCoin, Ripple, ETC</option>
</optgroup>
<optgroup label="Paypal">
<option value="Paypal">Paypal</option>
</optgroup>
<optgroup label="Giftcard">
<option value="Giftcard">Amazon, PSN, Steam, Battle.Net, G2A, ETC</option>
</optgroup>
</select>
<button onclick='//I want this to be whatever is selected in paymentMethod option group' class='btn btn-primary'>Submit</button>
I tried this JS code:
<script>
$(document).ready(function(){
$('#paymentMethod').on('change', function() {
if ( this.value == 'Paypal')
//.....................^.......
{
var paymentEr = 'Paypal()';
}
else if (this.value == 'Giftcard')
{
var paymentEr = 'Giftcard()';
} else {
var paymentEr = 'Paypal()';
}
});
});
document.write("<button onclick=' + paymentEr + "' class="btn btn-primary">Submit</button>");
</script>
Rather than change the onClick handler itself, I would make one handler that handles all of the cases (or if you want to have separate functions to organize your code, simply call those functions within the relevant condition blocks as follows):
function handleForm() {
const selected = document.getElementById("paymentMethod").value;
if (selected === 'Bitcoin') {
//handle bitcoin
}
else if (selected === 'Paypal') {
//handle Paypal
}
else if (selected === 'Giftcard') {
//handle GiftCard
}
}
<select class="form-control select2" id='paymentMethod'>
<optgroup label="Crypto">
<option value="Bitcoin">
Bitcoin, Etherum, Litecoin, DogeCoin, Ripple, ETC
</option>
</optgroup>
<optgroup label="Paypal">
<option value="Paypal">
Paypal
</option>
</optgroup>
<optgroup label="Giftcard">
<option value="Giftcard">
Amazon, PSN, Steam, Battle.Net, G2A, ETC
</option>
</optgroup>
</select>
<button onclick='handleForm()' class='btn btn-primary'>Submit</button>
On button click it checks the select element for the selected value and you can avoid inline javascript in the html code.Check my answer.
function init(){
let el = document.getElementById("paymentMethod");
let sbmBtn = document.getElementById("submitBtn");
sbmBtn.addEventListener('click',getSelectedValue);
function getSelectedValue(){
let selectedVal = el.options[el.selectedIndex].value;
if (selectedVal == 'Paypal'){
//var paymentEr = 'Paypal()';
alert(selectedVal);
}else if (selectedVal == 'Giftcard'){
//var paymentEr = 'Giftcard()';
alert(selectedVal);
} else {
//var paymentEr = 'Paypal()';
alert(selectedVal);
}
}
}
//DOM has been loaded
addEventListener('load',init);
<select class="form-control select2" id='paymentMethod'>
<optgroup label="Crypto">
<option value="Bitcoin">Bitcoin, Etherum, Litecoin, DogeCoin, Ripple, ETC</option>
</optgroup>
<optgroup label="Paypal">
<option value="Paypal">Paypal</option>
</optgroup>
<optgroup label="Giftcard">
<option value="Giftcard">Amazon, PSN, Steam, Battle.Net, G2A, ETC</option>
</optgroup>
</select>
<button id="submitBtn" class="btn btn-primary">Click</button>
I have created a dropdown and added a onclick="function name" to each of the options but however on selecting those options from the dropdown I am unable to get any response
This is the code that i have tried using:
<span onclick="myfunc('demo')">Sports</span>
<select name="sports">
<option value="none"></option>
<option value="cricket" onclick="myfunc('cricket')">Cricket</option>
<option value="football" onclick="myfunc('football')">Football</option>
<option value="volleyball" onclick="myfunc('volleyball')">Volleyball</option>
<option value="basketball" onclick="myfunc('basketball')">Basketball</option>
<option value="ttenis" onclick="myfunc('ttennis')">Table Tennis</option>
<option value="athletics" onclick="myfunc('atletics')">Athletics</option>
</select>
function myfunc(ft){
console.log(ft);
}
My only response is when I click the span i.e.Sports, and I get 'demo displayed in the output.
You may use change event to handle your each item. Please follow below code as your need
<select id="ddlSportsItems" name="sports">
<option value="0">None</option>
<option value="1">Cricket</option>
<option value="2">Football</option>
<option value="3">Volleyball</option>
<option value="4">Basketball</option>
<option value="5">Table Tennis</option>
<option value="6">Athletics</option>
</select>
$('#ddlSportsItems').change(function()
{
var selectedValue = parseInt(jQuery(this).val());
switch(selectedValue){
case 1:
Cricket();
break;
case 2:
Football();
break;
//etc...
default:
alert("catch default");
break;
}
});
function Cricket(){
alert("do your require stuff");
}
function Football(){
alert("do your require stuff");
}
Solution in javascript:
<select name="sports" onchange="myFunc(this)">
<option value="none"></option>
<option value="cricket">Cricket</option>
<option value="football">Football</option>
<option value="volleyball">Volleyball</option>
<option value="basketball">Basketball</option>
<option value="ttenis">Table Tennis</option>
<option value="athletics">Athletics</option>
</select>
<script>
function myFunc(select){
console.log(select.value);
}
</script>
Correct way to write this would be :
function myfunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
console.log(selectedValue);
if (selectedValue === 'cricket') {
alert("Cricket");
//Write your code for cricket
}
else if (selectedValue === 'football') {
alert("Football");
}
else if (selectedValue === 'volleyball') {
alert("Volleyball");
}
else if (selectedValue === 'basketball') {
alert("BasketBall")
}
else if (selectedValue === 'ttenis') {
alert("Table Tennis");
}
else if (selectedValue === 'athletics') {
alert("Athletics");
}
}
<span>Sports:</span>
<select id="selectBox" name="sports" onchange="myfunc();">
<option value="none"></option>
<option value="cricket">Cricket</option>
<option value="football">Football</option>
<option value="volleyball">Volleyball</option>
<option value="basketball">Basketball</option>
<option value="ttenis">Table Tennis</option>
<option value="athletics">Athletics</option>
</select>
You can try this.
function myfunc() {
alert($("#selectBox").val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Sports:</span>
<select id="selectBox" name="sports" onchange="myfunc();">
<option value="none"></option>
<option value="cricket">Cricket</option>
<option value="football">Football</option>
<option value="volleyball">Volleyball</option>
<option value="basketball">Basketball</option>
<option value="ttenis">Table Tennis</option>
<option value="athletics">Athletics</option>
</select>
I have two simple select inputs with same values, from 0% to 50% in both of them. I would like to control their values, so that when their values are combined, they do not exceed 50%. So no matter which of the two inputs is changed, the other one will change its value accordingly.
So let's say if first input has value 5% the second input should have value of 45% and vice versa.
I tried using .change function with an if/else if statement but i just cant get it to work. Needless to say i dont have much expirience with jquery.
HTML:
<select id="myselect1">
<option value="0">0%</option>
<option value="5">5%</option>
<option value="10">10%</option>
<option value="15">15%</option>
<option value="20">20%</option>
<option value="25">25%</option>
<option value="30">30%</option>
<option value="35">35%</option>
<option value="40">40%</option>
<option value="45">45%</option>
<option value="50">50%</option>
</select>
<select id="myselect2">
<option value="0">0%</option>
<option value="5">5%</option>
<option value="10">10%</option>
<option value="15">15%</option>
<option value="20">20%</option>
<option value="25">25%</option>
<option value="30">30%</option>
<option value="35">35%</option>
<option value="40">40%</option>
<option value="45">45%</option>
<option value="50">50%</option>
</select>
JS:
$('#myselect1').change(function(){
if ($this.value == '5'){
$('#myselect2').val('45');
}
else if ($this.value == '10'){
$('#myselect2').val('40');
}
else if ($this.value == '15'){
$('#myselect2').val('35');
}
else if ($this.value == '20'){
$('#myselect2').val('30');
}
else if ($this.value == '25'){
$('#myselect2').val('25');
}
else if ($this.value == '30'){
$('#myselect2').val('20');
}
else if ($this.value == '35'){
$('#myselect2').val('15');
}
else if ($this.value == '40'){
$('#myselect2').val('10');
}
else if ($this.value == '45'){
$('#myselect2').val('5');
}
else if ($this.value == '50'){
$('#myselect2').val('0');
}
});
$('#myselect2').change(function(){
if ($this.value == '5'){
$('#myselect1').val('45');
}
else if ($this.value == '10'){
$('#myselect1').val('40');
}
else if ($this.value == '15'){
$('#myselect1').val('35');
}
else if ($this.value == '20'){
$('#myselect1').val('30');
}
else if ($this.value == '25'){
$('#myselect1').val('25');
}
else if ($this.value == '30'){
$('#myselect1').val('20');
}
else if ($this.value == '35'){
$('#myselect1').val('15');
}
else if ($this.value == '40'){
$('#myselect1').val('10');
}
else if ($this.value == '45'){
$('#myselect1').val('5');
}
else if ($this.value == '50'){
$('#myselect1').val('0');
}
});
JS Fiddle
Your code will work if you changed
$this.value to this.value or assign this to $this (var $this = this);
However, this can be done in a very simple way
$('#myselect1, #myselect2').change(function() {
var who = this.id === 'myselect1' ? '#myselect2' : '#myselect1';
// if the ID of the changed select is #myselect1 who will be #myselect2 or vice versa.
$(who).val(50 - this.value); // change the value of the other select
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="myselect1">
<option value="0">0%</option>
<option value="5">5%</option>
<option value="10">10%</option>
<option value="15">15%</option>
<option value="20">20%</option>
<option value="25">25%</option>
<option value="30">30%</option>
<option value="35">35%</option>
<option value="40">40%</option>
<option value="45">45%</option>
<option value="50">50%</option>
</select>
<select id="myselect2">
<option value="0">0%</option>
<option value="5">5%</option>
<option value="10">10%</option>
<option value="15">15%</option>
<option value="20">20%</option>
<option value="25">25%</option>
<option value="30">30%</option>
<option value="35">35%</option>
<option value="40">40%</option>
<option value="45">45%</option>
<option value="50">50%</option>
</select>
Put a listener on both select boxes, do some maths to work out what the other value needs to be and the check to see which element we need to change.
http://jsfiddle.net/qj459ntg/3/
$('select').change(function(){
var MaxValue = 50
var CurValue = $(this).val();
var NewValue = MaxValue - CurValue;
if ($(this).is('#myselect1')) {
$('#myselect2').val(NewValue);
} else {
$('#myselect1').val(NewValue);
}
});
You have two issues going on.
You need to change all your statements to like:
if ($(this).val() == '5'){
$('#myselect2').val('45');
}
$this is not a valid selector in jquery.
.value cannot be inter,mingled with a jQuery selector.
$("#select_1").change(function() {
var select_1_value = $("#select_1").val();
var select_2_value = $("#select_2").val();
var value_1 = parseInt(select_1_value);
var value_2 = parseInt(select_2_value);
var sum_values = value_1 + value_2;
if (sum_values > 50)
{
var select_2_needed = value_2 - ((value_1 + value_2) - 50);
$("#select_2").val(select_2_needed + "%");
}
});
$("#select_2").change(function() {
var select_1_value = $("#select_1").val();
var select_2_value = $("#select_2").val();
var value_1 = parseInt(select_1_value);
var value_2 = parseInt(select_2_value);
var sum_values = value_1 + value_2;
if (sum_values > 50)
{
var select_1_needed = value_1 - ((value_1 + value_2) - 50);
$("#select_1").val(select_1_needed + "%");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id = "select_1">
<option>0%</option>
<option>5%</option>
<option>10%</option>
<option>15%</option>
<option>20%</option>
<option>25%</option>
<option>30%</option>
<option>35%</option>
<option>40%</option>
<option>45%</option>
<option>50%</option>
</select>
<select id = "select_2">
<option>0%</option>
<option>5%</option>
<option>10%</option>
<option>15%</option>
<option>20%</option>
<option>25%</option>
<option>30%</option>
<option>35%</option>
<option>40%</option>
<option>45%</option>
<option>50%</option>
</select>
You will need something like this (see snippet linked with).
$('#myselect1').change(function(){ if($(this).val() < 50 ){ var value
= 50 - $(this).val(); $('#myselect2').val(value); }else if($(this).val() == 50){ $('#myselect2').val(0); } });
$('#myselect2').change(function(){ if($(this).val() < 50 ){ var value
= 50 - $(this).val(); $('#myselect1').val(value); }else if($(this).val() == 50){ $('#myselect1').val(0); } });
Hope this will help you.
I'm coding a simple form with html w/javascript and have been working on this one aspect for about two days. I've seen numerous ideas across the internet but none seem to give me an idea of what to do. So hoping you guys can help.
Basically what has to happen is when USA is selected the form should require that a numeric postal code be entered or else it refuses submission. Below is my code so far, sorry its pretty lengthy.
<label id="stateLabel" for="state">State</label>
<select name="state" id="state" onchange="validateState()">
<option value="">Select a State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<div id="stateError" class="errorMessage"></div>
<br />
<label id="countryLabel" for="country">Country</label>
<select name="country" id="country" onchange="validateCountry()">
<option value="">Select a Country</option>
<option value="US">United States of America</option>
<option value="CAN">Canada</option>
<option value="MEX">Mexico</option>
</select>
<div id="countryError" class="errorMessage"></div>
<br />
<label id="postCodeLabel" for="postCode">Postal Code</label>
<input type="text" name="postCode" id="postCode" onblur="validatePostCode()" onfocus="resetPostCode()" />
<div id="postCodeError" class="errorMessage"></div>
<br />
Javascript
var lStateLabel;
var ddState;
var dStateError;
var lCountryLabel;
var ddCountry;
var dCountryError;
var lPostCodeLabel;
var iPostCode;
var dPostCodeError;
function validatePostCode()
{
if((isNaN(iPostCode.value) == false) && (iPostCode.value.length == 5))
{
resetPostCode();
return true;
}
else
{
lPostCodeLabel.style.color = "red";
dPostCodeError.innerHTML = "Your Postal Code must be numeric and 5 integers long.";
return false;
}
}
Here, I think this is what you're looking for:
HTML:
<form name="myForm" action="assignment-js-form-success.html" onsubmit="return validateForm()" method="post">
<label id="firstNameLabel" for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName" onblur="validateFirstName()" onfocus="resetFirstName()" />
<div id="firstNameError" class="errorMessage"></div>
<br />
<label id="lastNameLabel" for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" onblur="validateLastName()" onfocus="resetLastName()" />
<div id="lastNameError" class="errorMessage"></div>
<br />
<label id="addressLabel" for="address">Address</label>
<input type="text" name="address" id="address" onblur="validateAddress()" onfocus="resetAddress()" />
<div id="addressError" class="errorMessage"></div>
<br />
<label id="cityLabel" for="city">City</label>
<input type="text" name="city" id="city" onblur="validateCity()" onfocus="resetCity()" />
<div id="cityError" class="errorMessage"></div>
<br />
<label id="stateLabel" for="state">State</label>
<select name="state" id="state" onchange="validateState()">
<option value="">Select a State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<div id="stateError" class="errorMessage"></div>
<br />
<label id="countryLabel" for="country">Country</label>
<select name="country" id="country" onchange="validateCountry(); if (iPostCode.value !== '') validatePostCode();">
<option value="">Select a Country</option>
<option value="US">United States of America</option>
<option value="CAN">Canada</option>
<option value="MEX">Mexico</option>
</select>
<div id="countryError" class="errorMessage"></div>
<br />
<label id="postCodeLabel" for="postCode">Postal Code</label>
<input type="text" name="postCode" id="postCode" onblur="validatePostCode()" onfocus="resetPostCode()" />
<div id="postCodeError" class="errorMessage"></div>
<br />
<label id="emailLabel" for="email">Email Address</label>
<input type="text" name="email" id="email" value="" onblur="validateEmail()" onfocus="resetEmail()" />
<div id="emailError" class="errorMessage"></div>
<br />
<label id="passwordLabel" for="password">Password</label>
<input type="text" name="password" id="password" onblur="validatePassword()" onfocus="resetPassword()" />
<div id="passwordError" class="errorMessage"></div>
<br />
<label id="passwordConfirmLabel" for="passwordConfirm">Confirm Password</label>
<input type="text" name="passwordConfirm" id="passwordConfirm" onblur="validatePasswordConfirm()" onfocus="resetPasswordConfirm()" />
<div id="passwordConfirmError" class="errorMessage"></div>
<br />
<input type="submit" value="Submit" id="submitButton" value="Check"/>
</form>
<div id="errorMessage"></div>
JavaScript:
function initialization() {
lFirstNameLabel = document.getElementById("firstNameLabel");
iFirstName = document.getElementById("firstName");
dFirstNameError = document.getElementById("firstNameError");
lLastNameLabel = document.getElementById("lastNameLabel");
iLastName = document.getElementById("lastName");
dLastNameError = document.getElementById("lastNameError");
lAddressLabel = document.getElementById("addressLabel");
iAddress = document.getElementById("address");
dAddressError = document.getElementById("addressError");
lCityLabel = document.getElementById("cityLabel");
iCity = document.getElementById("city");
dCityError = document.getElementById("cityError");
lStateLabel = document.getElementById("stateLabel");
ddState = document.getElementById("state");
dStateError = document.getElementById("stateError");
lCountryLabel = document.getElementById("countryLabel");
ddCountry = document.getElementById("country");
dCountryError = document.getElementById("countryError");
lPostCodeLabel = document.getElementById("postCodeLabel");
iPostCode = document.getElementById("postCode");
dPostCodeError = document.getElementById("postCodeError");
lEmailLabel = document.getElementById("emailLabel");
iEmail = document.getElementById("email");
dEmailError = document.getElementById("emailError");
lPasswordLabel = document.getElementById("passwordLabel");
iPassword = document.getElementById("password");
dPasswordError = document.getElementById("passwordError");
lPasswordConfirmLabel = document.getElementById("passwordConfirmLabel");
iPasswordConfirm = document.getElementById("passwordConfirm");
dPasswordConfirmError = document.getElementById("passwordConfirmError");
} // end initialization()
window.validateForm = function() {
noErrors = true;
if (validateFirstName() == false) noErrors = false;
if (validateLastName() == false) noErrors = false;
if (validateAddress() == false) noErrors = false;
if (validateCity() == false) noErrors = false;
if (validateState() == false) noErrors = false;
if (validateCountry() == false) noErrors = false;
if (validatePostCode() == false) noErrors = false;
if (validateEmail() == false) noErrors = false;
if (validatePassword() == false) noErrors = false;
if (validatePasswordConfirm() == false) noErrors = false;
return noErrors;
}; // end validateForm()
window.validateFirstName = function() {
if (iFirstName.value.length > 1) {
resetFirstName();
return true;
} else {
lFirstNameLabel.style.color = "red";
dFirstNameError.innerHTML = "First Name should be more than one character";
return false;
} // end if
}; // end validateFirstName()
window.resetFirstName = function() {
lFirstNameLabel.style.color = "black";
dFirstNameError.innerHTML = "";
}; // end resetFirstName()
window.validateLastName = function() {
if (iLastName.value.length > 1) {
resetLastName();
return true;
} else {
lLastNameLabel.style.color = "red";
dLastNameError.innerHTML = "Last Name should be more than one character!";
return false;
} // end if
}; // end validateLastName()
window.resetLastName = function() {
lLastNameLabel.style.color = "black";
dLastNameError.innerHTML = "";
}; // end resetLastName()
window.validateAddress = function() {
if (iAddress.value.length > 1) {
resetAddress();
return true;
} else {
lAddressLabel.style.color = "red";
dAddressError.innerHTML = "Address must be greater than one character.";
return false;
} // end if
}; // end validateAddress()
window.resetAddress = function() {
lAddressLabel.style.color = "black";
dAddressError.innerHTML = "";
}; // end resetAddress()
window.validateCity = function() {
if (iCity.value.length > 1) {
resetCity();
return true;
} else {
lCityLabel.style.color = "red";
dCityError.innerHTML = "You must input a valid city name.";
return false;
} // end if
}; // end validateCity()
window.resetCity = function() {
lCityLabel.style.color = "black";
dCityError.innerHTML = "";
}; // end resetCity()
window.validateState = function() {
if (ddState.selectedIndex > 0) {
resetState();
return true;
} else {
lStateLabel.style.color = "red";
dStateError.innerHTML = "You must select a state!";
return false;
} // end if
}; // end validateState()
window.resetState = function() {
lStateLabel.style.color = "black";
dStateError.innerHTML = "";
}; // end resetState()
window.validateCountry = function() {
if (ddCountry.selectedIndex > 0) {
resetCountry();
return true;
} else {
lCountryLabel.style.color = "red";
dCountryError.innerHTML = "You must select a country!";
return false;
} // end if
}; // end validateCountry()
window.resetCountry = function() {
lCountryLabel.style.color = "black";
dCountryError.innerHTML = "";
}; // end resetCountry()
window.validatePostCode = function() {
// get currently selected country
var countrySelectElem = document.getElementById('country');
var countryValue = countrySelectElem.options[countrySelectElem.selectedIndex].value;
// if US, require 5-digit postal code
if (countryValue === 'US') {
if (isNaN(iPostCode.value) == false && iPostCode.value.length == 5) {
resetPostCode();
return true;
} else {
lPostCodeLabel.style.color = "red";
dPostCodeError.innerHTML = "Your US Postal Code must be numeric and 5 integers long.";
return false;
} // end if
} else {
// require non-empty for other countries
if (iPostCode.value !== '') {
resetPostCode();
return true;
} else {
lPostCodeLabel.style.color = "red";
dPostCodeError.innerHTML = "Your Postal Code must be non-empty.";
return false;
} // end if
} // end if
}; // end validatePostCode()
window.resetPostCode = function() {
lPostCodeLabel.style.color = "black";
dPostCodeError.innerHTML = "";
}; // end resetPostCode()
window.validateEmail = function() {
var pattern = /^([a-zA-Z0-9_.-]+)#([a-zA-Z0-9+_.-]+)\.([a-zA-Z]+)$/;
if (pattern.test(iEmail.value)) {
resetEmail();
return true;
} else {
lEmailLabel.style.color ="red";
dEmailError.innerHTML = "Valid Email address is required!";
return false;
} // end if
}; // end validateEmail()
window.resetEmail = function() {
lEmailLabel.style.color = "black";
dEmailError.innerHTML = "";
}; // end resetEmail()
window.validatePassword = function() {
if (iPassword.value.length >= 6) {
resetPassword();
return true;
} else {
lPasswordLabel.style.color = "red";
dPasswordError.innerHTML = "Password should be at least 6 characters!";
return false;
} // end if
}; // end validatePassword()
window.resetPassword = function() {
lPasswordLabel.style.color = "black";
dPasswordError.innerHTML = "";
}; // end resetPassword()
window.validatePasswordConfirm = function() {
if (iPasswordConfirm.value === iPassword.value) {
resetPasswordConfirm();
return true;
} else {
lPasswordConfirmLabel.style.color = "red";
dPasswordConfirmError.innerHTML = "Passwords must match!";
return false;
} // end if
}; // end validatePasswordConfirm()
window.resetPasswordConfirm = function() {
lPasswordConfirmLabel.style.color = "black";
dPasswordConfirmError.innerHTML = "";
}; // end resetPasswordConfirm()
// actual onload code
initialization();
http://jsfiddle.net/gpyd956e/
The relevant code is this:
window.validatePostCode = function() {
// get currently selected country
var countrySelectElem = document.getElementById('country');
var countryValue = countrySelectElem.options[countrySelectElem.selectedIndex].value;
// if US, require 5-digit postal code
if (countryValue === 'US') {
if (isNaN(iPostCode.value) == false && iPostCode.value.length == 5) {
resetPostCode();
return true;
} else {
lPostCodeLabel.style.color = "red";
dPostCodeError.innerHTML = "Your US Postal Code must be numeric and 5 integers long.";
return false;
} // end if
} else {
// require non-empty for other countries
if (iPostCode.value !== '') {
resetPostCode();
return true;
} else {
lPostCodeLabel.style.color = "red";
dPostCodeError.innerHTML = "Your Postal Code must be non-empty.";
return false;
} // end if
} // end if
}; // end validatePostCode()
Because the validation of the postal code depends on the currently-selected country, you have to retrieve it in the validation function and then branch on it. After that, you can do exactly the validation you need for each country.
Also, in order to keep the postal code field error message up-to-date for country changes, I added this to the onchange handler for the country field:
if (iPostCode.value !== '') validatePostCode();
This dynamically re-validates the postal code field for changes to the country field, but only if the user has actually typed something into the postal code field (you wouldn't want a change to the country field to trigger a postal code error message if the user hasn't typed any postal code yet).
I also made various fixes for things like typos and inconsistent function naming and calling, and adapted the code to jsFiddle, which I believe runs the JavaScript in a synthesized window.onload callback, requiring some changes to ensure true globalness where necessary.
The ZIP code should only be required when USA is selected? Otherwise, you can use HTML validation constraints for input attributes like max, min, required, type or even pattern (for RegExp).
is it possible to change the limit the value of the dropdown2 when the dropdown1 changes?
here is my code
<!--DROPDOWN 1-->
<p class="">From</p>
<select name="From" id="From" onChange="displayVal(this)">
<option value="any">Any</option>
<option value="none">None</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
<option value="30000">£30,000</option>
<option value="40000">£40,000</option>
<option value="50000">£50,000</option>
<option value="60000">£60,000</option>
<option value="70000">£70,000</option>
<option value="80000">£80,000</option>
<option value="90000">£90,000</option>
<option value="100000">£100,000</option>
<option value="110000">£110,000</option>
<option value="120000">£120,000</option>
<option value="130000">£130,000</option>
<option value="140000">£140,000</option>
<option value="150000">£150,000</option>
<option value="150001">£150,000+</option>
</select>
<!--DROPDOWN 2-->
<p class="">To</p>
<select name="To" id="To">
<option value="any">Any</option>
<option value="none">None</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
<option value="30000">£30,000</option>
<option value="40000">£40,000</option>
<option value="50000">£50,000</option>
<option value="60000">£60,000</option>
<option value="70000">£70,000</option>
<option value="80000">£80,000</option>
<option value="90000">£90,000</option>
<option value="100000">£100,000</option>
<option value="110000">£110,000</option>
<option value="120000">£120,000</option>
<option value="130000">£130,000</option>
<option value="140000">£140,000</option>
<option value="150000">£150,000</option>
<option value="150001">£150,000+</option>
</select>
I want is when I change dropdown1 to none the dropdown2 option will only show none and no other more.
And I also want is if I change the value of dropdown1 to an amount, for example 30000, dropdown2 will show only the values that are greater that 30000 including the option any.
Is there a way to do this in javascript or jQuery?
sorry. I'm new at javascript and jQuery.. Thank you in advance!
Demo: http://jsfiddle.net/LsaLA/1/
Code:
function setTo() {
var f = $('#From').val();
var t = $('#To');
t.children().hide();
if( f == 'none' ) {
t.children('[value="none"]').show();
t.val('none');
}
else if( t == 'any' ) {
t.children().show();
t.val('any');
}
else {
f = parseInt(f, 10);
t.children().each(function() {
if( $(this).val() == 'any' ) {
$(this).show();
t.val('any');
}
else {
var v = parseInt($(this).val(), 10);
if(!isNaN(v) && v >= f) {
$(this).show();
}
}
});
t.val('any');
}
}
$('#From').change(setTo);
//call it on load as well
setTo();
try this: http://jsfiddle.net/F6xnL/4/
$("#From").change(function() {
$("#To").attr("disabled", false).children().each(function() {
$(this).attr('disabled', false);
});
if ($(this).val() === 'any') return;
if ($(this).val() === 'none') {
$("#To").val("none").attr("disabled", true);
return;
}
var pound = parseInt($(this).val());
$("#To").children().each(function() {
var val = $(this).val();
if (val === 'none' || val === 'any') {
$(this).attr('disabled', true); return;
}
if (parseInt($(this).val()) <= pound) {
$(this).attr('disabled', true);
}
});
});
$('#From').change(function(){
if($(this).val() == 'none'){
$('#To').prop('disabled', true);
}else if((true == $('#To').prop('disabled')) && ($(this).val() != 'none')){
$('#To').prop('disabled', false);
}
$('#To option').each(function(){
if($(this).val() < $('#From').val()){
$(this).hide(0);
}else{
if($(this).css('display') == 'none'){
$(this).show(0);
}
}
});
});
Untested, but this should work. I'm a bit verbose.