Having problems selecting values from a <select> to put into JavaScript - javascript

This is my code. I am attempting to get values from the drop down menu and text, put them into the equation. What am I doing wrong so that the function is stopping half way through. I know it is probably really easy to solve but I cannot find a solution anywhere. Please help.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h3> Question 6 </h3>
<h4> How long can you safely tan for? </h4>
<script language="javascript">
function calculate5() {
var skin = document.getElementById("skinselect");
var skinselect = Math.floor(skinselect.options[skinselect.selectedIndex].value);
var cloud = document.getElementById("cloudselect");
var cloudselect = Math.floor(cloudselect.options[cloudselect.selectedIndex].value);
var temp = Math.floor(document.getElementById("temp").value);
var time = ((skinselect + cloudselect) * temp) - 50;
alert("Your safe sunbaking time is " + time + " minutes");
}
</script>
<select id="skinselect">
<option value="error">Skin type: 0 is light, 5 is dark </option>
<option value="0"> 0 </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option>
</select>
<select id="cloudselect">
<option value="error">Cloud Cover: 0 is clear, 5 is overcast </option>
<option value="0"> 0 </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option>
</select>
<input type="text" value="Temperature (C)" id="temp" size="16">
<input type="button" value="Calculate" onClick="calculate5()">
</body>
</html>

inside your function you need to access option from select id
var skin = document.getElementById("skinselect");
var skinselect = Math.floor(skin.options[skin.selectedIndex].value);
var cloud = document.getElementById("cloudselect");
var cloudselect = Math.floor(cloud.options[cloud.selectedIndex].value);
var temp = Math.floor(document.getElementById("temp").value);
var time = ((skinselect + cloudselect) * temp) - 50;
you can refer
Get selected value in dropdown list using JavaScript?

In your function:
var skinselect = Math.floor(skin.options[skin.selectedIndex].value);
and
var cloudselect = Math.floor(cloud.options[cloud.selectedIndex].value);

document.getElementById("skinselect").value contains its selected option value.
Set a default value in case any option hasn't already been selected.
Eg.
<select id="skinselect" value="error">
(because error is the default value due to the fact it's on the top of the options list)

Related

javascript to dynamically change the dropdown

Attached the screenshot of my web page.
In that picture, under Regression type dropdown list box, there are three values consider 1, 2 and 3
So if I select 1 or 2, drop down below that "F1" should not appear. If value3, then it should appear.
To do this I have added onload under body tag.
HTML CODE:
<div class = "cl-regr" id="div-regr">
<select name = "regr" id="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value = "1"> ips </option>
<option value = "2"> ips sanity </option>
<option value = "3"> Features </option>
</select>
</div>
<div class = "cl-ftr" id="div-ftr" onchange="displayFeatureList()">
<select name = "ftr" class = "cl2" id="drop-ftr">
<option value = "f1"> F1 </option>
<option value = "f2"> F2 </option>
<option value = "f3"> F3 </option>
<option value = "f4"> F4 </option>
</select>
</div>
RESPECTIVE SCRIPT IN SEPARATE .js FILE:
function func1(){
$(".cl-ftr").each(function() {
var that = $(this);
that.find("div.cl2").style.visibility="hidden";
});
};
function displayFeatureList(){
var d_obj = document.getElementById("drop_reg").value;
var op = d_obj.options[d_obj.selectedIndex].value;
if (op == 3){
document.getElementById("drop_ftr").style.visibility = 'visible';
}
else{
document.getElementById("drop_ftr").style.visibility = 'hidden';
}
};
where I'm calling func1 from body tag
<body onload="func1()">
Problems I'm facing are,
1)Whenever the page loads, the "F1" dropdown list box of first row is hiding (ie, ClientIP - 10.213.174.90)
2) If I change the value, displayFeatureList function is not making any effects.
Any help would be much appreciated!!
you are syntax was wrong
$(this) is jquery object style.visiblity its dom function
Use with css() jquery function .style.visiblity is not a jquery object.
For better my suggestion use css .cl2{visiblity:hidden} instead of js
cl2 class in select element not with div so remove the div with cl2 in selector like find('cl2')
fix the id name typo - instead of _
Add change event with first select
Get the value from dropdown direct call the selectelement.value.no need specify index
function func1() {
$(".cl-ftr").each(function() {
var that = $(this);
that.find(".cl2").css('visibility', "hidden");
});
};
function displayFeatureList() {
var d_obj = document.getElementById("drop-regr").value
if (d_obj == '3') {
document.getElementById("drop-ftr").style.visibility = 'visible';
} else {
document.getElementById("drop-ftr").style.visibility = 'hidden';
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="func1()">
<div class="cl-regr" id="div-regr">
<select name="regr" id="drop-regr" onchange="displayFeatureList()">
<option selected="selected" disabled>-----Select-----</option>
<option value = "1"> ips </option>
<option value = "2"> ips sanity </option>
<option value = "3"> Features </option>
</select>
</div>
<div class="cl-ftr" id="div-ftr" >
<select name="ftr" class="cl2" id="drop-ftr">
<option value = "f1"> F1 </option>
<option value = "f2"> F2 </option>
<option value = "f3"> F3 </option>
<option value = "f4"> F4 </option>
</select>
</div>
With all respect, your code quality is not very good.
It's filled with typos (changing _ to -, missing single letters for ids etc.) This way, nothing will ever work. Take more care.
An id has to be unique. If an id appears twice in the same HTML document,
the document is not valid by definition. (It still loads though, but you have to expect errors.) You maybe want to keep the ids an add a dynamic number (row number)to keep them unique
If you use jQuery, use it by default. Don't mix up jQuery(func1()) and JS DOM methods(displayFeatureList)
I reduced your code to the following (I commented the whole JS code for better understanding):
$(document).ready(function() { //run when page loading is complete
$(".regessionTypeCell").each(function() { //for each regessionTypeCell class (parent div, might be a table cell in your case)
$(this).find(".drop-regr").change(function(event) { //set onChange function for the containing drop-regr class
var conditionalDropdown = $(this).find(".cl-ftr"); //get the conditional dropdown element
if ($(this).find(".drop-regr").val() == 3) { //if selected index is equal 3
conditionalDropdown.show(); //show dropdown
} else {
conditionalDropdown.hide(); //hide dropdown
}
}.bind($(this))); //bind this to the inner function
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="regessionTypeCell">
<div class="cl-regr">
<select name="regr" class="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value="1"> ips </option>
<option value="2"> ips sanity </option>
<option value="3"> Features </option>
</select>
</div>
<div class="cl-ftr" style="display:none">
<select name="ftr" class="drop-ftr">
<option value="f1"> F1 </option>
<option value="f2"> F2 </option>
<option value="f3"> F3 </option>
<option value="f4"> F4 </option>
</select>
</div>
</div>
<div class="regessionTypeCell">
<div class="cl-regr">
<select name="regr" class="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value="1"> ips </option>
<option value="2"> ips sanity </option>
<option value="3"> Features </option>
</select>
</div>
<div class="cl-ftr" style="display:none">
<select name="ftr" class="drop-ftr">
<option value="f1"> F1 </option>
<option value="f2"> F2 </option>
<option value="f3"> F3 </option>
<option value="f4"> F4 </option>
</select>
</div>
</div>

How to swap between select inputs

I want to have a swap button as in Google Translate,
this button should swap between the selection inputs in a form
each selector shows a list of currencies. I want to click and simply swap between the values.
i.e.
<select name="from" id="from" class="form-control" onchange="selectValue(this);">
<option value="ILS"> Israeli Shekel (₪) </option>
<option value="USD" selected=""> US Dollar (USD) </option>
<option value="EUR"> Euro (EUR) </option>
</select>
<select name="to" id="to" ONCHANGE="goto(this.form)" class="form-control">
<option value="ILS" selected=""> Israeli Shekel (₪) </option>
<option value="USD"> US Dollar (USD) </option>
<option value="EUR"> Euro (EUR) </option>
<option value="GBP"> British Pound (GBP) </option>
</select>
<button type="button" class="btn btn-lg center-block w100" onclick="swap();">Swap</button>
JS:
<script>
var a = document.getElementById("from").index;
// var value = a.options[a.selectedIndex].value;
var b = document.getElementId("to").index;
var c = b;
function swap() {
document.getElementById("from").selectedIndex = c;
document.getElementById("to").selectedIndex = a;
}
</script>
When clicked it changes one value only, is it the way to do it with index?
I'd like this to run over Phone Gap.
You should try below jquery code.
$('button').click(function(){
var from = $('#from').val(),
to = $('#to').val();
$('#from').val(to);
$('#to').val(from);
});

Force unique selections from three SELECT boxes

I have three simple SELECT boxes:
<select class="select_choice" id="1">
<option value="0">
-- Please select
</option>
<option data-cost="15" value="6">
Leisure Sports £15
</option>
<option data-cost="0" value="1">
Three Days at the Movies £0
</option>
<option data-cost="10" value="3">
Table Tennis Camp £10
</option>
<option data-cost="6" value="4">
Beach Sports £6
</option>
<option data-cost="22" value="5">
You CAN Teach an Old Dog new Tricks £22
</option>
</select><select class="select_choice" id="2">
<option value="0">
-- Please select
</option>
<option data-cost="15" value="6">
Leisure Sports £15
</option>
<option data-cost="0" value="1">
Three Days at the Movies £0
</option>
<option data-cost="10" value="3">
Table Tennis Camp £10
</option>
<option data-cost="6" value="4">
Beach Sports £6
</option>
<option data-cost="22" value="5">
You CAN Teach an Old Dog new Tricks £22
</option>
</select><select class="select_choice" id="3">
<option value="0">
-- Please select
</option>
<option data-cost="15" value="6">
Leisure Sports £15
</option>
<option data-cost="0" value="1">
Three Days at the Movies £0
</option>
<option data-cost="10" value="3">
Table Tennis Camp £10
</option>
<option data-cost="6" value="4">
Beach Sports £6
</option>
<option data-cost="22" value="5">
You CAN Teach an Old Dog new Tricks £22
</option>
</select>
As you can see, they're the same SELECT (in terms of attached OPTIONS) with a different ID.
These drop-downs are for students to pick their 3 preferred choices (in order, i.e. 1st choice is favourite, 2nd choice is 2nd favourite and so on).
What I'm trying to achieve is when a student selects "TABLE TENNIS CAMP", it sets that same option in the other SELECTs to "disabled".
I can do that well enough using the following code:
$(document).ready(function() {
$('.select_choice').change(function() {
var $mc = $('span#maximumCost');
var maximumCost = parseInt( $mc.text() );
var $o = $(this).find(":selected");
var clickedSelectID = $(this).attr("id");
var obj = {};
obj.id = $o.val();
obj.selectID = clickedSelectID;
obj.name = $o.text().split(/\u00A3/g)[0];
obj.cost = $o.data("cost");
$('#choice-' + clickedSelectID).text(obj.name);
$('#choice-' + clickedSelectID).data("challenge_id", obj.id);
if( obj.cost > maximumCost )
$mc.text(obj.cost);
$('.select_choice').not(this).each(function() {
$(this).find('option[value="' + obj.id + '"]').css('background-color', 'red');
});
});
});
What I can't get my head around is how to re-enable the relevant OPTIONs when a user un-selects a choice.
I've thought about storing some jQuery data() or an array about the states of the three SELECT boxes but I'm just not bright enough to figure out how to then check those states and update the SELECT boxes accordingly. I'm also not sure if that's necessary; I suspect there's a relatively straightforward answer here.
jsFiddle: http://jsfiddle.net/Lqu4c0eb/1/
As you said, you can use the data api to store the previous selection
$('.select_choice').not(this).find('option[value="' + obj.id + '"]').prop("disabled", true);
$('.select_choice').not(this).find('option[value="' +$(this).data('prev') + '"]').prop("disabled", false);
$(this).data('prev', obj.id)
Demo: Fiddle

How to limit options in a <select> based on another option selection

I'm trying to limit the number of options based on another selection. For instance in this example "How many credits is the class you skipped?" should be limited to equal or less than the previous question "How many total credits are you taking this semester?". So if I'm only taking 9 credits on semester the second question of how many credits I'm skipping should be equal or less than the 9 credits for the whole semester.
Any help will be greatly appreciated.
Here is the jsfiddle: http://jsfiddle.net/k7tDP/1/
Here is the JS:
function calculateCost() {
'use strict';
// enter annual tuition
var $annualTuition = parseInt($('#annual_tuition').val());
// tuition per semester
var semesterTuition = Math.round($annualTuition / 3);
// total number of credits for semester
var $semesterCredits = parseInt($('#semester_credits').val());
// cost of a single credit
var singleCreditCost = semesterTuition / $semesterCredits;
// total credits for class being skipped
var $skippedTotalCredits = parseInt($('#skipped_total_credits').val());
// total cost for class being skipped
var skippedTotalCreditsCost = $skippedTotalCredits * singleCreditCost;
// number of times skipped class meets per week
var $skippedWeekDays = parseInt($('#skipping_class_meet').val());
// from date
var fromDate = $('#from').datepicker('getDate');
// to date
var toDate = $('#to').datepicker('getDate');
// calculate number of weeks in date range (semester) using 'from / to' dates
var skippedWeeks = Math.ceil((toDate - fromDate) / (1000 * 7 * 60 * 60 * 24));
console.log(skippedWeeks);
// total number of days in semester for class being skipped
//var $skippedTotalDays = parseInt($('#skipped_total_days').val());
var skippedTotalDays = $skippedWeekDays * skippedWeeks;
// (total cost of class) / (total number of class days in semester) = cost of class
var skippedSingleClassCost = skippedTotalCreditsCost / skippedTotalDays;
return skippedSingleClassCost.toFixed(2);
}
$(function() {
'use strict';
$('#from').datepicker({
defaultDate: '+1w',
changeMonth: true,
numberOfMonths: 1,
onSelect: function() {
//toDate = $(this).datepicker('getDate');
}
});
$('#to').datepicker({
defaultDate: '+1w',
changeMonth: true,
numberOfMonths: 1,
onSelect: function() {
//fromDate = $(this).datepicker('getDate');
}
});
$('#cost').on('click', function() {
$('.costFigure').fadeIn('fast');
$('#costTotal').html(calculateCost());
});
});
Here is the html:
<form id="costForm" action="#" onsubmit="#">
<div>
<label for="annual_tuition">What is your annual tuition (estimated)?</label>
<div class="styled_select">
<select name="annual_tuition" id="annual_tuition" value="tuition amount" autofocus>
<option value="0"> </option>
<option value="5000">$5,000</option>
<option value="10000">$10,000</option>
<option value="15000">$15,000</option>
<option value="20000">$20,000</option>
<option value="25000">$25,000</option>
<option value="30000">$30,000</option>
<option value="35000">$35,000</option>
<option value="40000">$40,000</option>
<option value="45000">$45,000</option>
<option value="50000">$50,000</option>
</select>
</div>
</div>
<div>
<label for="semester_credits">How many total credits are you taking this semester?</label>
<div class="styled_select">
<select name="semester_credits" id="semester_credits" value="" tabindex="2">
<option value="0"> </option>
<option value="3">3 credits</option>
<option value="6">6 credits</option>
<option value="9">9 credits</option>
<option value="12">12 credits</option>
<option value="13">13 credits</option>
<option value="14">14 credits</option>
<option value="15">15 credits</option>
<option value="16">16 credits</option>
<option value="17">17 credits</option>
<option value="18">18 credits</option>
</select>
</div>
</div>
<div>
<label for="skipped_total_credits">How many credits is the class you skipped?</label>
<div class="styled_select">
<select name="skipped_total_credits" id="skipped_total_credits" value="" tabindex="2">
<option value="0"> </option>
<option value="3">3 credits</option>
<option value="6">6 credits</option>
<option value="9">9 credits</option>
<option value="12">12 credits</option>
<option value="13">13 credits</option>
<option value="14">14 credits</option>
<option value="15">15 credits</option>
<option value="16">16 credits</option>
<option value="17">17 credits</option>
<option value="18" disabled>18 credits</option>
</select>
</div>
</div>
<div>
<label for="skipping_class_meet">How many times a week does the class you skipped meet?</label>
<div class="styled_select">
<select name="skipping_class_meet" id="skipping_class_meet" value="" tabindex="2">
<option value="0"> </option>
<option value="1">1 time a week</option>
<option value="2">2 times a week</option>
<option value="3">3 times a week</option>
<option value="4">4 times a week</option>
<option value="5">5 times a week</option>
</select>
</div>
</div>
<div class="dateRange clearfix">
<label>Between what months are you enrolled in this class?</label>
<div style="width: 48%; float: left;">
<label for="from">From:</label>
<input type="text" id="from" name="from">
</div>
<div style="width: 48%; float: right;">
<label for="to">To:</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="cost" type="button">Calculate</button>
</div>
<div class="costFigure">
<h1>your missed class cost you $<span id="costTotal"></span></h1>
</div>
</form>
On change of your dropdown fire a onchange trigger and on the basis of values make the 2nd dropdown enable or disabled.
$("#semester_credits").change(function () {
var $this=this;
$("#skipped_total_credits").children().each(function(){
$(this).attr("disabled",parseInt($this.value) < parseInt(this.value));
});
});
Check the fiddle here
EDIT
$this.value contains the value selected from "semester_credits" dropdown, now For each child of "skipped_total_credits", I am checking if that value is less than the children value then make it disabled, i.e attr("disabled", true) else make that children enabled.
I've created a quick function to help you out, there may be a neater way to do this, but it does the job quite nicely!
Onchange of the element #semester_credits I grab the value (number of semesters credits and then loop over the next select box and remove the ones that have a higher value that the chosen one, I use a global var to cache the removed options in case the user changes their minds and we need to add them back in.
$(function () {
var savedOpts = "";
$('#semester_credits').change(function() {
//Add all options back in;
if( savedOpts ) {
$('#skipped_total_credits').append(savedOpts);
savedOpts = "";
}
//Return false if blank option chosen;
if( $(this).val() === "0" )
return false;
var chosenCreds = parseInt($(this).val());
$('#skipped_total_credits option').each(function() {
var thisCred = parseInt($(this).val());
if(thisCred > chosenCreds) {
//Remove
savedOpts += $(this)[0].outerHTML;
$(this).remove();
}
});
});
Here an updated fiddle
p.s the example Kai Hartmann suggests is also a nice way to achieve this.
If you want the drop-down list for a question to change based on previous answer, you need to add an onchange event to each select element which would update another drop-down. This should then call a function which removes or adds elements in your form.
Otherwise, you can add a validation function for your Calculate button.

onchange not working for drop down menu?

I'm trying to make it so that when a selection is made from my dropdown menu, text will display accordingly inside my textarea, for now I've been trying to just get one of them to work.
PROBLEM: It won't display the string from the array inside the textarea. Is the problem within this code?
The drop down menu:
<select id="dropdown" onchange="getFrames();">
<option value="1" selected="selected"> Blank </option>
<option value="2"> Exercise </option>
<option value="3"> Juggler </option>
<option value="4"> Bike </option>
<option value="5"> Dive </option>
</select>
The textarea :
<textarea id="textstage" rows="80" cols="20"> </textarea>
JavaScript :
I have these global variables.
var theStage = document.getElementById("textstage");
var getDrop = document.getElementById("dropdown");
and then I have this function.
function getFrames(){
var dropSel = getDrop.options[getDrop.selectedIndex].value;
if(dropSel === 2){
theStage.value = ANIMATIONS["Exercise"];
}
The array being referenced is a global array from another js file.
Try:
var theStage,getDrop;
function getFrames() {
var dropSel = getDrop.options[getDrop.selectedIndex].innerHTML;//+getDrop.value;
theStage.value = ANIMATIONS[dropSel];
}
//Place the selection part on load callback
window.onload = function () {
theStage = document.getElementById("textstage");
getDrop = document.getElementById("dropdown");
}
Demo
You can just use getDrop.value instead of doing getDrop.options[getDrop.selectedIndex].value.
=== is strict equality comparison meaning "2" === 2 will be false as in your case.
Seems like you are looking for the option text to look up the value based on this as key in your object Animation. So you can just do getDrop.options[getDrop.selectedIndex].innerHTML
Your document selection code should be inside window.onload or after the element in the html
I made a minor change to your html by omitting the inline event handler, and instead added it to the javascript.
html:
<select id="dropdown">
<option value="1" selected="selected"> Blank </option>
<option value="2"> Exercise </option>
<option value="3"> Juggler </option>
<option value="4"> Bike </option>
<option value="5"> Dive </option>
</select>
<textarea id="textstage" rows="80" cols="20"> </textarea>
Also, in the javascript, I took away the strict equality (===) and made it just (==).
javascript:
var theStage = document.getElementById("textstage");
var getDrop = document.getElementById("dropdown");
getDrop.addEventListener("change",getFrames);
function getFrames(){
var dropSel = getDrop.options[getDrop.selectedIndex].value;
if(dropSel == 2){
theStage.value = ANIMATIONS["Exercise"];
}
}
Hopefully it should work now for you.

Categories