I have a situation where I need the user to enter either a specific number (their monthly bill for example) or, in the case that they dont have a specific number, to choose from a dropdown of averages by state. I am unsure how to write an if/else statement that firsts ask if the specific input is defined, and in lieu of a text input, to check for the dropdown value.
Edit: this is my second attempt at getting something workable, no luck :/
JS
var val = document.getElementById('perKWhCost').value;
var select_value = document.querySelector('#selection').value;
var getMonthlyCost = function(){
if (val){
getMonthlyCost = val;
}
else{
getMonthlyCost = select_value;
}
console.log(getMonthlyCost);
}
var getAnnualSavings = getMonthlyCost * finalAnnualEnergy;
HTML
<div class="form-group">
<label name="monthlyCost" for="inputKWh">Per kWh cost(see energy bill)</label>
<p>This should look like "<em>$0.11/kWh</em>"</p>
<input type="text" value="" class="form-control" id="perKWhCost" placeholder="0.11">
<label for="state">Or select a state</label>
<select name="Cost" id="selection">
<option value=".11">Alabama</option>
<option value=".19">Alaska</option>
<option value=".11">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value=".20">Connecticut</option>
<option value=".13">Delaware</option>
<option value=".13">District Of Columbia</option>
<option value=".12">Florida</option>
<option value=".11">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value=".11">Illinois</option>
<option value=".11">Indiana</option>
<option value=".11">Iowa</option>
<option value=".12">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value=".18">Maine</option>
<option value="MD">Maryland</option>
<option value=".19">Massachusetts</option>
<option value=".15">Michigan</option>
<option value=".12">Minnesota</option>
<option value="MS">Mississippi</option>
<option value=".09">Missouri</option>
<option value="MT">Montana</option>
<option value=".09">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value=".16">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value=".09">North Dakota</option>
<option value=".12">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value=".14">Pennsylvania</option>
<option value=".18">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value=".10">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value=".17">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>
<input type="button" value="Calculate!" id="submit" class="btn btn-default btn-lg" onclick="doMath();">
</form>
Note: the JS above is part of the function doMath which is not fully shown here. Additionally, ignore that not every selection has a decimal value yet, that will be changed in the working code.
This is the gist of what I need. I need to check if there is a value in the text field, if there is I want getMonthlyCost to store that value (preferably only if its a number). If there is no input in the text box I want the code to check the selector dropdown and take the users selection and pass that value to getMonthlyCost.
You could do something like this
var getMonthlyCost = function(){
var val = document.getElementById('perKWhCost').value;
var select_value = document.getElementById('selection');
var parsedValue=parseFloat(val);//parse if user entered valid float or nothing
if (parsedValue!=NaN & val!=""){// check parsed value
return val;
}
else{
if(select_value.selectedIndex != null) { //check if user has selected DropDown and get selected value if yes
return select_value.options[select_value.selectedIndex].value;}
else {//nothing entered}
}
}
function doMath() {
var getAnnualSavings = getMonthlyCost * 12;
console.log(getAnnualSavings);
}
It looks like you assigned "getMonthlyCost" as a function and assumed it was not one in the call when trying to get the "getMonthlyCost". The code below should work
var getMonthlyCost = function(){
var val = document.getElementById('perKWhCost').value;
var select_value = document.querySelector('#selection').value;
var returnValue = !!val ? val : select_value;
console.log(returnValue);
return returnValue;
}
var getAnnualSavings = getMonthlyCost() * finalAnnualEnergy;
Or you could do
var monthlyCost = document.getElementById("perKWCost").value || document.querySelector("#selection").value;
var annualSavings = monthlyCost * finalAnnualEnergy;
monthlyCost will take the take the first one if both are defined and if the first one is "", undefined or null, it will take the second one;
I hope this helps
Example: https://jsfiddle.net/12znp29s/
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_()
Related
<select>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sept</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
I have the list of the month and they have numeric value to represent month number. I need to Mar to be selected by typing 3 on keyboard when it is focused.
Now I have to type "m" to select Mar or first letter of any month to select that month.
You can have a look at the fiddle here : https://jsfiddle.net/tn0gL34h/1/
check this i have modified ahmad's answer little bit, this will work for 2 digits also. source
var typingTimer;
var doneTypingInterval = 1000;
var $input = $('select');
var keys = '';
$input.on('keyup', function (e) {
keys += parseInt(e.key);
console.log(keys);
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$input.on('keydown', function () {
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
if(keys != ''){
//do something
$input.val(parseInt(keys));
keys='';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sept</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
For months from January to September, the following code will work, because they all require a single keystroke.
For the others, Month 10, 11, and 12, you will have to select manually.
$('select').on('keyup',function(e){
// this will only work for Jan --> Sep
// becuase Oct --> Dec require two digits
$(this).val(parseInt(e.key));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sept</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
As far as I know, the only reliable way to do this would be to use a javacript select menu replacement plugin. The techniques for capturing keypresses while a select is focused work on some browsers but not others (see more discussion on this here: keydown event in drop down list). In fact, though others have mentioned it works for them, Ahmad's answer above does not work on my browser (Chrome 49 / OS X 10.8).
Here is an example of how you could do this with a modified matcher method using Select2:
$('select').select2({
matcher: function(params, data) {
if ($.trim(params.term) === '') {
return data;
} else if (data.id.indexOf(params.term) === 0) {
// this is where the magic happens
// we return options where search input matches
// the beginning of the value
return data;
} else {
return null;
}
}
});
select {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<select>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sept</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
I'm looping through each select with the class specialMenuCat and grabbing its value.
I'm using console.log() which shows the correct value but I'm not sure how to store this as a variable to use later.
<select class="specialMenuCat" name="menuCategory[]">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
$('select.specialMenuCat').change(function(){
$('select.specialMenuCat').each(function(){
var catVal = $(this).val();
console.log(catVal);
});
});
An example of the console log is;
apples (5)
oranges (4)
peach (5)
banana (5)
I tried setting the vars first and then incrementing them but it didn't work. My attempt;
$('select.specialMenuCat').change(function(){
var apples = 0;
$('select.specialMenuCat').each(function(apples){
var catVal = $(this).val();
if(catVal == apples) { apples++; }
console.log(catVal);
});
});
initialize apple variable outside the onchange scope
because every time its re-initialize thats why value not increase
var apple = 0;
var apple = 0;
$('select.specialMenuCat').change(function() {
$('select.specialMenuCat').each(function() {
var catVal = $(this).val();
if (catVal == "apples") {
apple++;
}
console.log(catVal);
});
console.log(apple);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="specialMenuCat" name="menuCategory[]">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
Declare an object and push value into it every change by increment in its occurrence
in result you can get the value by accessing the property name by example number of apples the should be like result['apple']
See belwon snippet :
$('select.specialMenuCat').change(function(){
$(".as-console").html("");
result = {};
$('select.specialMenuCat').each(function(){
if(!this.value) return;
val = result[this.value];
result[this.value] = typeof(val)== 'undefined' ? 1 : ++val;
});
console.log(result);
for (var prop in result) {
if (result.hasOwnProperty(prop)) {
console.log("number of "+ prop + " is: " + result[prop])
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peach">Peach</option>
<option value="banana">Banana</option>
</select>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>>
<option value="date">Dates</option>
</select>
<select class="specialMenuCat" name="menuCategory[]">
<option value=""></option>
<option value="melon">Melon</option>
<option value="oranges">Oranges</option>>
<option value="date">Dates</option>
</select>
the apples variable is inside your change function, so it won't exist outside your change function. This should work:
var apples = 0;
$('select.specialMenuCat').change(function(){
apples = 0; //reset, because you will start a new count
$('select.specialMenuCat').each(function(item){
var catVal = $(this).val();
if(catVal == "apples") { apples++; }
console.log(catVal);
});
});
function SomeOtherEvent(){
console.log(apples);
}
In the following Demo:
As suggested by Mr. McCrossan, create an Object Literal that has the fruit variables stored within. Keep your variables outside a function if you plan to increment/decrement the values. Referencing a value outside a function will create a closure which in turn causes a value to exist past the runtime of the function and thereby insuring a growing/shrinking value to build upon.
Register the select.fruit to the 'change' event
Get the value of the changed select with either this or event.target (in this Demo this is used).
Run the value through a switch() (I picked switch because it illustrates intentions very well).
On each matching case the value of the fruit property is incremented in the F Object as well as the corresponding output.
Demo
Details commented in Demo
/* Object literal stores each value
|| Note it is outside of a function
*/
var F = {
apples: 0,
oranges: 0,
peaches: 0,
bananas: 0
};
// Any change events that happen on a .fruit, callback runs
$('.fruit').on('change', fruitCount);
// This callback passes the Event Object (not used in this Demo)
function fruitCount(e) {
// "this" is the <select> currently changed
var currentPick = this.value;
switch (currentPick) {
/* if the value of "this" is "apples"...
|| increment the 'apples' property of the F Object
|| and then increment the value of output#A
|| But if it isn't apples fall onto the next case
*/ // Same applies to the other fruits
case 'apples':
F.apples++;
$('#A').val(F.apples);
break;
case 'oranges':
F.oranges++;
$('#O').val(F.oranges);
break;
case 'peaches':
F.peaches++;
$('#P').val(F.peaches);
break;
case 'bananas':
F.bananas++;
$('#B').val(F.bananas);
break;
default:
break;
}
}
select,
label,
output {
font: inherit;
}
label {
display: inline-block;
width: 8ch
}
<fieldset>
<legend>Fruit-O-Rama</legend>
<label>Apples: </label><output id='A'></output><br>
<label>Oranges: </label><output id='O'></output><br>
<label>Peaches: </label><output id='P'></output><br>
<label>Bananas: </label><output id='B'></output><br>
</fieldset>
<select class="fruit" name="menu0[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<br>
<select class="fruit" name="menu1[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<br>
<select class="fruit" name="menu2[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<br>
<select class="fruit" name="menu3[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<br>
<select class="fruit" name="menu4[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<br>
<select class="fruit" name="menu5[]">
<option value=""></option>
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="peaches">Peaches</option>
<option value="bananas">Bananas</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My HTML page contents two select options as follows.
It has two li selection as #age1 and #age2 with contents 18 to 30 ages.
I want to make it as if user select a age from #age1, #age2 minimum value set to same value(not only pragmatically, even in the display on select). That means user cant see below values than the #age1 selected value.
Eg:- if user select 25 from #age1, #age2 selector values starts from 25 to 30.
HTML
<li>
<label class="label">Age</label>
<select id="age1">
<option value="18">18</option><option value="19">19</option>
<option value="20">20</option><option value="21">21</option>
<option value="22">22</option><option value="23">23</option>
<option value="24">24</option><option value="25">25</option>
<option value="26">26</option><option value="27">27</option>
<option value="28">28</option><option value="29">29</option>
<option value="30">30</option>
</select>
<label class="label">To</label>
<select id="age2">
<option value="18">18</option><option value="19">19</option>
<option value="20">20</option><option value="21">21</option>
<option value="22">22</option><option value="23">23</option>
<option value="24">24</option><option value="25">25</option>
<option value="26">26</option><option value="27">27</option>
<option value="28">28</option><option value="29">29</option>
<option value="30">30</option>
</select>
</li>
J-query
$("#age1").change(function() {
});
$("#age2").change(function() {
});
$("#age1").change(function() {
var getStartVal = $(this).val();
$("#age2").val(getStartVal).find("option").show().each(function() {
if($(this).attr("value")<getStartVal) {
$(this).hide();
}
});
});
You can use the above jquery to make it working.
Working Fiddle : https://jsfiddle.net/wpam11k7/
ameenulla0007 answer is a good one but I would edit you html like this
<select id="age1">
<option value="18">18</option><option value="19">19</option>
<option value="20">20</option><option value="21">21</option>
<option value="22">22</option><option value="23">23</option>
<option value="24">24</option><option value="25">25</option>
<option value="26">26</option><option value="27">27</option>
<option value="28">28</option><option value="29">29</option>
<option value="30">30</option>
</select>
<label class="label">To</label>
<select id="age2">
</select>
</li>
Then use this jQuery to add just the selections you want rather than hiding
jQuery("#age1").change(function() {
var bottomEnd = jQuery("#age1").val();
var topEnd = jQuery("#age1").val() + 30;
for( $i=bottomEnd; $i < topEnd; $i++ {
jQuery('#age-2').append('<option value="'+jQuery('#age1').val()+'">'+jQuery('#age1').val()+'</option>');
}
});
You could just use the html from your first age list to populate the second one, since they appear to be the same:
$("#age1").on("change", function() {
/* get the value of age1 */
var val = $(this).val();
/* get all the ages after the selected one
and add them to the selected age */
var $selected = $(this).find("option:selected");
var $available = $selected.add( $selected.nextAll() ).clone();
/* save the selected value of age2 */
var selected2 = $("#age2").find("option:selected").val();
/* append the html from age1 selection to the
age2 list, and try to keep the old selection value */
$("#age2")
.html( $available )
.find("option[value='" + selected2 + "']")
.prop("selected", true);
});
You can see it running here; https://jsfiddle.net/1qsnzyjh/ :)
I have a form with three inputs, one for City, State, and Zipcode. Using javascript I need a simple way to check if the input for City contains a value. If the input does contain a value, I then need to check if State contains a value. If city contains a value, but state does not, I then need to trigger an alert box asking the user to enter a state.
This is my form code, Thanks in advance!!
<form action="home.php" method="post" name="location">
Please enter....<br /><br /><label>city:
<input type="text" name="city" size="10"/></label>
<br /><label>state:
<select id="state" name="state">
<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></label><br />
or <br />zipcode
<input type="text" name="zipcode" size="6" /><br />
<br /><input type="submit" value="search" />
</form>`
We get the user to enter zipcode first and then auto-fill city and state. Here is the code from zipcodeapi.com/examples:
<script type="text/javascript">//<![CDATA[
$(function() {
// IMPORTANT: Fill in your client key
var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";
var cache = {};
var container = $("#example1");
var errorDiv = container.find("div.text-error");
/** Handle successful response */
function handleResp(data)
{
// Check for error
if (data.error_msg)
errorDiv.text(data.error_msg);
else if ("city" in data)
{
// Set city and state
container.find("input[name='city']").val(data.city);
container.find("input[name='state']").val(data.state);
}
}
// Set up event handlers
container.find("input[name='zipcode']").on("keyup change", function() {
// Get zip code
var zipcode = $(this).val().substring(0, 5);
if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
{
// Clear error
errorDiv.empty();
// Check cache
if (zipcode in cache)
{
handleResp(cache[zipcode]);
}
else
{
// Build url
var url = "https://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";
// Make AJAX request
$.ajax({
"url": url,
"dataType": "json"
}).done(function(data) {
handleResp(data);
// Store in cache
cache[zipcode] = data;
}).fail(function(data) {
if (data.responseText && (json = $.parseJSON(data.responseText)))
{
// Store in cache
cache[zipcode] = json;
// Check for error
if (json.error_msg)
errorDiv.text(json.error_msg);
}
else
errorDiv.text('Request failed.');
});
}
}
}).trigger("change");
});
//]]>
Zip Code Distance
It will be better to use HTML5 required form field attribute. I create the jsfiddle for your.
Note that, as it stands, they will have always selected a state, since Alabama is selected by default. You can add an option with no value and a label of "Pick a state" to change this.
With that advice taken and an id "city" on your city input
var city = document.getElementById('city'),
state = document.getElementById('state'),
cityFilled = city.value !== ''
stateBlank = state.value ==='';
if(cityFilled && stateBlank){
alert("Enter a zipcode, chump");
}
Using pure js you can write the code as
var val = document.getElementById("name").value; // get value
if(val == "") { // check its value, if null
alert("please write something here"); // alert the user..
}
And do that similarly for each and every input.
You need to add the id to each element to make the JS capture the element.
I have a select tag and I want to check if a moth is selected.
<select name="Birth_Month">
<option value="" SELECTED>- Month -</option>
<option value="January">January</option>
<option value="Fabruary">Fabruary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
So do this:
if (document.registration_form.Birth_Month.value === '')
{
alert('Please fill select Month!');
}
But this JavaScript for some select-s work and for some of them, does not. Obviously, when the "- Month -" is selected the it returnes "- Month -" insted of "" (empty string). What I have done wrong? What is the best way of checking the tag's selection?
Browsers didn't always have a .value property for <select> - we used to have to get the value of the <option>:
var birthMonth = document.registration_form.Birth_Month;
if (birthMonth.options[birthMonth.selectedIndex].value === '') {
// something
}
I use jQuery .val() now. I don't remember which browsers lack the select.value property, and maybe those browsers are so old that we don't need to worry about them anymore. But jQuery doesn't use select.value - it loops through each of the options to find the selected option's value.
Of course, if you know you'll always have a single blank option as the first option, just check for selectedIndex==0.
I believe integers are a better practice for option values. Anyhow, the snippet below doesn't care if your default option value is an empty string or a zero value.
var birthMonth = document.registration_form.Birth_Month;
if(birthMonth.options[birthMonth.selectedIndex].value === false){
alert('Please fill select Month!');
}
You do not need to use 'selectedIndex'
<select name="Birth_Month">
<option value="" SELECTED>- Month -</option>
<option value="January">January</option>
<option value="Fabruary">Fabruary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
if (document.getElementById('Birth_Month').value === '')
{
alert('Please fill select Month!');
}
OR
<select name="Birth_Month">
<option value="they_did_not_select_anything" SELECTED>- Month -</option>
<option value="January">January</option>
<option value="Fabruary">Fabruary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
if (document.getElementById('Birth_Month').value === 'they_did_not_select_anything')
{
alert('Please fill select Month!');
}