Can Select options have Multiple Values? - javascript

I'm wondering if it's possible to have code where the Select option has 2 different value (which effect 2 different things)
Basically, I'm trying to create an option where depending on the select choice, it changes the price and also changes the link that pressing the button will go to.
I found this code on one of the posts here and it works perfectly, but I'm looking to add a Price in between the select menu and the button which is also effected by the select choice.
Eg.
1 Year Only - $50 [Button links to correct purchase link]
Subscription (Billed Annually) - $45/pa [Button links to correct purchase link]
Sorry if i'm not explaining it very well.
<select id="menu">
<option selected="selected" disabled="">Please choose an option</option>
<option value="https://checkout-1-year">1 Year</option>
<option value="https://checkout-subscription">Subscription (Billed Annually)</option>
</select>
<input type="button" id="goBtn" value="Purchase">
<script type="text/javascript">
var goBtn = document.getElementById("goBtn");
var menu = document.getElementById("menu");
goBtn.onclick = function() {
window.location = menu.value;
}
</script>

They can't have two values, but what you can do is set the value and a data- attribute, which can store any string you like and then be retrieved using the data-* Attribute API.
Here's an example:
const list = document.getElementById("menu");
console.log(list.options[1].value, list.options[1].dataset.value);
console.log(list.options[2].value, list.options[2].dataset.value);
<select id="menu">
<option selected="selected" disabled="">Please choose an option</option>
<option value="https://checkout-1-year" data-value="something">1 Year</option>
<option value="https://checkout-subscription" data-value="something else">Subscription (Billed Annually)</option>
</select>

Related

How do you pass a value to a hidden form field when a certain option is selected?

I am new to javascript and cannot find an easy-to-understand answer.
I would like a certain value to get passed to a hidden field when a user selects a certain option from the select dropdown.
I know that there are if/else statements but I'm not sure if that would be used in this situation.
For example: I have a select dropdown of a list of states.
<select name="HomeState" required>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
As you can see, any option other than California will be rated at a value of 1.
I would like it to where if the user selects the option of California, then the value of $300 will get passed to a hidden form field.
<input name="AmountNeeded" type="hidden" value="300" />
If they select anything other than California, the hidden field would get passed $100
<input name="AmountNeeded" type="hidden" value="100" />
How would I implement this logic? Would it be using if/else statement? I am new and don't exactly know how to set that up.
To keep this simple you could assign ids to the <select> and hidden <input> and listen to the change event via onchange() on the <select> with a function call.
And based on the selected item, change the value of hidden input.
NOTE: To test the snippet out I have removed the type="hidden". Do place it back.
function homeSelected(){
const home = document.getElementById("homeSelector").value;
if(home == 5){
document.getElementById("amountNeeded").value = 300;
}else{
document.getElementById("amountNeeded").value = 100;
}
}
<select id="homeSelector" name="HomeState" onchange="homeSelected()" required>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
<input id="amountNeeded" name="AmountNeeded" value="100" />
You can do this as follows:
<select name="HomeState" required onChange=myFunction(this)>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
Javascript code is:
<script>
function myFunction(x) {
val = x.options[x.selectedIndex].text;
if(val == 'California')
document.getElementsByName("AmountNeeded")[0].value = 300
else
document.getElementsByName("AmountNeeded")[0].value = 100
}
</script>
If else statement is good for you if you are sure that All other states have value 1 except California. If all states may have different values like some states may have 1 or some may have 2 or some may have 3, then there may be other alternatives to solve this like you can pass give one more attribute data-src-amount to options and give amount to data-src-amount. You can create options like <option value="1" data-src-amount="100">Alabama</option> and in script, you can fetch data-src-amount on select change event instead of if-else statement.

How to Set the Default Value of a Dropdown List with Javascript

<select class="form-control sprites-arrow-down" id="TaskFitToWork" name="TaskFitToWork" onchange="getInstructions();" >
<option selected disabled value="">Select Fit To Work</option>
{{range $key, $val := .vm.FitToWorkArray}}
<option id="{{index $.vm.FitToWorkKey $key}}" value="{{$val}}" >{{$val}} </option>
{{end}}
</select>
This is my HTML code to fill a dropdown list using golang.
var fitToWorkName = vm.FitToWorkName
document.getElementById("TaskFitToWork").value = fitToWorkName;
This is the JavaScript code . Note, that here vm.FitToWorkName contains value to be filled in the drop down list. I tried to set the default fill for the dropdown list but it is not working. Please help me solve this issue.
One may set the default value of a dropdown list with either HTML or JavaScript, as this example illustrates. Initially, the code sets the default option using HTML and later at the user's discretion the default can be reset with JavaScript. At the outset the critical part of the code involves applying "selected" to the desired default option. If the user chooses a different option, then clicking the button that restores the default option activates some JavaScript. A simple, one-liner function uses the select element's selectedIndex property and sets it to indicate the second option. Since the array of options use zero-based indexing that index has a value of one.
var d = document;
d.g = d.getElementById;
var btn = d.g("btn");
var mySelect = d.g("mySelect");
function getInstructions(){
return true;
}
function restoreDefault(){
mySelect.selectedIndex = 1;
}
btn.onclick = restoreDefault;
option:first {
background: #fff;
color:#009;
}
select {
background:#fff;
color:#009;
}
<select id="mySelect" class="form-control sprites-arrow-down" id="TaskFitToWork" name="TaskFitToWork" onchange="getInstructions();" value>
<option id="val" value="" disabled>Select Fit To Work</option>
<option id="val" value="somevalue" selected>Some Value </option>
<option id="val" value="anothervalue" >Another Value </option>
<option id="val" value="morevalue" >More Value </option>
</select>
<button id="btn">Restore Default</button>

Multiple options from one drop down giving alternate results - Javascript/html

I'm looking to have separate sections of my form become visible dependant on the selection from a drop down menu.
Currently i'm having two issues, its only hiding the first area i want hidden and also i'm struggling with the syntax to get the multiple options working using if statements.
Am i looking at this the right way or is there an easier way of doing this.
In the code below i've only got 2 if statements as i've been struggling to get that correct so haven't done it for all 8 options i need to.
function showfield(name){
if (name=='Supplier meetings') {
document.getElementById('div1').style.display="block";
} else {
document.getElementById('div1').style.display="none";
if (name=='Product meetings') {
document.getElementById('div2').style.display="block";
} else {
document.getElementById('div2').style.display="none";
}
}
}
function hidefield() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
document.getElementById('div3').style.display='none';
document.getElementById('div4').style.display='none';
document.getElementById('div5').style.display='none';
document.getElementById('div6').style.display='none';
document.getElementById('div7').style.display='none';
document.getElementById('div8').style.display='none';
}
in my html i have:
<body onload="hidefield()">
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1">Worked hours</option>
<option value="2">Overtime</option>
<option value="3">Sickness</option>
<option value="4">Unpaid leave</option>
<option value="5">Compassionate leave</option>
<option value="6">Holiday inc bank holidays</option>
<option value="7">Team meetings</option>
<option value="8">One to ones</option>
<option value="9">One to one prep</option>
<option value="10">Huddles</option>
<option value="Supplier meetings">Supplier meetings</option>
<option value="Product meetings">Product meetings</option>
<option value="Training/coaching">Training/coaching</option>
<option value="Handling other peoples cases">Handling other peoples cases</option>
<option value="15">Project work</option>
<option value="16">Surgery time for GK</option>
<option value="17">Letter checks and feedback</option>
<option value="18">MI/Reporting/RCA</option>
</select>
Then divs that contain the parts i need displayed off each option.
Hope that makes sense.
Thanks
Instead of writing condition for each option value, you can use the value directly in selecting the div that is to be shown:
function showfield(name){
hidefield();
document.getElementById( 'div-' + name).style.display="block";
}
For this to work, your id's should match up with corresponding option values.
e.g. <option value="1">1</option>
corresponding div:
<div id="div-1"></div>
You can add a data-div attribute to every option which will be ID of respective div which will be shown and other divs will be hidden.
You need a class on every div so they can be hidden using that class name except the div which will be shown based on selection.
HTML
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1" data-div="one">Worked hours</option>
<option value="2" data-div="two">Overtime</option>
</select>
<div id="one">First Div</div>
<div id="two">Second Div</div>
Javascript
function showfield(val)
{
var divID = $("select[name=acti]").find("option[value='" + val + "']").attr("data-div");
$(".divClass").hide();//You can also use hidefield() here to hide other divs.
$("#" + divID).show();
}

How to use document.getElementsByTagName(

I want to use this function to work on all my drop down lists. Problem: the first drop down works okay, but hen I try select any option in the 2nd drop down selections. It places the value from the first group in the span of the second group. I want the span to have the value from its own group. I would like to use this on multiple groups.
The code below does not work properly. the phone number display okay but when i try to select the parts, the value of the phone number is displayed, no matter what the selection is.
I want the phone number when i select phones, and parts when i select parts.
Thank you
<script>function displayResult(xspan,xselect)
{
var x=document.getElementById(xselect).selectedIndex;
alert(x);
var newTxt = document.getElementsByTagName("option")[x].value;
document.getElementById(xspan).innerHTML = newTxt;
//alert(document.getElementsByTagName("option").length);
}
</script>
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
<option value="">Phone Numbers</option>
<optgroup label="Shipping">
<option value=" - 800-463-3339">FedEx</option>
<option value=""></option>
</optgroup>
</select>
<span id="ShowPhone"></span>
<select id="myParts" onchange="displayResult('ShowParts','myParts')">
<option value="">Qik Parts list</option>
<optgroup label="BATT">
<option value="1">1</option>
<option value="2">1</option>
<option value="2">1</option>
<option value="2"><1/option>
</optgroup>
</select>
<span id="ShowParts"></span>
Mostly comments:
When you do:
var newTxt = document.getElementsByTagName("option")[x].value;
then document.getElementsByTagName("option") returns all the options in the document, you probably only want the ones for the select in question. But the options for a select are available as a collection, so you can do:
selectElement.options[x].value;
But that is unnecessary unless you are dealing with very old browsers or IE where there are no value attributes. Just use selectElement.value.
Where you have:
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
you can instead do:
<select id="myPhones" onchange="displayResult('ShowPhone', this.value)">
so that you pass the current value of the select directly to the function. Then the function can be:
function displayResult(id, value) {
document.getElementById(id).innerHTML = value;
}
This should work, though I haven't tested it.
function displayResult(spanId, selectId) {
document.getElementById(spanId).innerHTML = document.getElementById(selectId).value;
}

How to create dropdown menu that appears based on answer from another dropdown menu

I'm trying to create a page where you users have to make multiple selections that are based on each other. How do you create a form such that a specific type of dropdown menu #2 appears based on the user's selection in dropdown menu #1.
For example, lets say a user has to choose a "product category" and a "product subcategory". If a user chooses "bedding" from the first drop down menu, a second drop-down menu automatically appears with choices like "bed, mattress, pillow".
To further this example, lets say the user chose "electronics" instead of "bedding." Then the second-drop down menu would have choices like "tv, mp3 players, computers".
How would one go about doing something like that? Is it something you would do in HTML/CSS or some other form?
Thanks for the help!
EDIT - I'm using Django / Python to construct this website along with HTML, CSS, and Javascript.
You can use a combination of HTML and JavaScript (JSFIDDLE):
<select id="opts" onchange="showForm()">
<option value="0">Select Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<div id="f1" style="display:none">
<form name="form1">
<select id="opts" onchange="showForm()">
<option value="0">Select Option</option>
<option value="1">Option 1A</option>
<option value="2">Option 1B</option>
</select>
</form>
</div>
<div id="f2" style="display:none">
<form name="form2">
<select id="opts" onchange="showForm()">
<option value="0">Select Option</option>
<option value="1">Option 2A</option>
<option value="2">Option 2B</option>
</select>
</form>
</div>
<script type="text/javascript">
function showForm() {
var selopt = document.getElementById("opts").value;
if (selopt == 1) {
document.getElementById("f1").style.display = "block";
document.getElementById("f2").style.display = "none";
}
if (selopt == 2) {
document.getElementById("f2").style.display = "block";
document.getElementById("f1").style.display = "none";
}
if (selopt == 0) {
document.getElementById("f2").style.display = "none";
document.getElementById("f1").style.display = "none";
}
}
</script>
Like this? Created a js fiddle.
http://jsfiddle.net/wigster/MeTQQ/
It grabs the value of the drop down box, and then if it matches the rule, it'll set the other drop-down box to show, if not, keeps that other drop-down box hidden.
If you wish to use jQuery, you can use this test case:
http://jsfiddle.net/exXmJ/
The way I see it there are two ways to go. Delete the dropdown and exchange it for a new one, or hide/show two different dropdowns. Alexander covered the second method so I won't go into that.

Categories