Javascript multiple select boxes - javascript

I tried searching for an answer to this for a while, but to no avail.
I'm trying to do a simple online calculator (that calculates some photovoltaic panels energy), but I'm stuck in something simple (I'm new to Javascript although I worked with Flash's ActionScript 3.0 for a while).
What I need done is a html select that defines which other select group appears in the page. Something like this (obviously this doesn't work, just setting an example):
HTML
<html>
<body>
<select id="test1" onclick="checkField()">
<option>Selected A Group</option>
<option>Selected B Group</option>
</select>
<script>//insert second group here</script>
</body>
</html>
Javascript
function checkField(){
var temp = document.getElementById('test1').value;
if(temp === "Selected A Group"){
//insert code to "echo" the first optional select group
} else {
//insert code to "echo" the second optional select group
}
}
Sorry if its a bit confusing, but I cant really explain all that well.
Here is an example of what I would want, where selecting a option makes the other fields change accordingly: http://www.toshiba.eu/innovation/download_drivers_bios.jsp

you are almost there, actually javascript doesn't "echo" values directly, it does log values using console.log(your value); to a debug console, similar to AS2 trace() if my memory isn't failing.
To "output" information to the document you should have a look into document.write
When you use document.write it will directly write to the documents end.
The "correct" way would be to create a DOM element, with the elements you want inside it, and then append it to the desired element. Have a look at the comments
<!-- Be Aware to use the onchange trigger on select boxes, if you use onclick the function will run, even
if you didn't really chose any option -->
<select id="test1" onchange="checkField()">
<!-- Is good to have a first non-value option, better to trigger the onchange event, if you have
Select A Group as first option and you click on it, it didn't really "Change", you would have to
pick B Group and then A Group again to trigger the onchange event correctly. -->
<option value="">-- select an option --</option>
<!-- You can have a value attribute on the options, so it's easy to process when programming
while displaying a more detailed description to the users -->
<option value="A">Selected A Group</option>
<option value="B">Selected B Group</option>
</select>
<!-- We create an empty element where we are gonna place the new Select -->
<div id="newSelect"></div>
<!-- By Placing the Javascript on the end of <body>, we ensure that all the DOM elements loaded before running the script -->
<script>
function checkField(){
var newSelect = document.getElementById('newSelect'); //targeting container;
var temp = document.getElementById('test1').value;
//Some tasks we do always the option chose is not the first custom one, so we don't have to repeat it
//on the two If's below
if(temp !== ""){
// We remove the select if we placed one already before, so we can add the new one,
// For example if we chose B Group but changed our mind and Chose A Group later.
if(oldChild = newSelect.getElementsByTagName('select')[0]){
oldChild.remove();
}
var select = document.createElement("select");
select.setAttribute('id', 'newSelect');
}
if(temp === "A"){
//you could do JUST:
//body.innerHTML = "all the html you want in here" instead of all the code following;
//but all those code is supposed to be the "correct way" of adding elements to the HTML,
//Google a bit about that for detailed explanations
var option1 = document.createElement("option");
option1.value = 1;
option1.text = "Option 1";
var option2 = document.createElement("option");
option1.value = 2;
option2.text = "Option 2";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
} else {
var option1 = document.createElement("option");
option1.value = 3;
option1.text = "Option 3";
var option2 = document.createElement("option");
option1.value = 4;
option2.text = "Option 4";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
}
}
</script>
Of course there are ways to make this slightly shorter, using loops if your data to ouput has a pattern, but lets do it the "simple" way so you get a grasp of Javascript.
Hope all this helped you!!

Demo here:
http://jsfiddle.net/3GkrX/
Just about the same as Mevins.... changed to switch/case though
html:
<select id="test1" id="name" onchange="checkField()">
<option>----</option>
<option>Selected A Group</option>
<option>Selected B Group</option>
</select>
<div id="optional">Please select!</div>
JS:
function checkField(){
var temp = document.getElementById('test1').value;
switch(temp){
case "Selected A Group":
document.getElementById("optional").innerHTML="<select name='optionalA'><option>1</option><option>2</option></select>";
break;
case "Selected B Group":
document.getElementById("optional").innerHTML="<select name='optionalB'><option>3</option><option>4</option></select>";
break
default:
document.getElementById("optional").innerHTML="Please select!";
break;
}
}
Also added the second group as a real option, and a default as "please select". may or may not be necessary in your case

Here is the demo http://codepen.io/anon/pen/izAHo
your doing it almost right.
You should put the onclick event on the option tag to trigger changes based on the option selected.
HTML
<html>
<body>
<select id="test1">
<option onclick="checkField()">Selected A Group</option>
<option>Selected B Group</option>
</select>
<select id="test2">
<option onclick="check2Field()">Selected C Group</option>
<option>Selected D Group</option>
</select>
<script>//insert second group here</script>
</body>
</html>
JS
function checkField(){
var temp = document.getElementById('test1').value;
if(temp === "Selected A Group"){
document.getElementById('test2').innerHTML="<option>Selected halloooo Group</option>";
} else {
//insert code to "echo" the second optional select group
}
}
Check out my demo for more clarity.

Related

JaveScript Select the dropdown list by the text of options

Is it possible to select the dropdown list by using the display-text of the options in the console(JavaScript)?
In my workplace, I need to fill a web form every day. But the options are too much to load, so I hope to use the Chrome console to select the option instead of using the mouse to click.
For now, I can use Value to select the option, but when I try to use the text, it fails.
The HTML sample and the JavaScript I used are as below. Could someone help?
Success - document.querySelector("#sel").value = 123
Fails - document.querySelector("#sel").text = "Product A"
<select>
<option value="123"> Product A </option>
<option value="243"> Product B </option>
<option value="212"> Product C </option>
<option value="466"> Product D </option>
</select>
Array.from(document.querySelectorAll('option')).find(el => el.textContent === 'Product A');
Truly sorry for the confusing example.
After trying lots of solutions, the final coding as below:
var txt = prompt();
for (i = 0; i < document.querySelector("#sel").options.length; i++) {
if(document.querySelector("#sel").options[i].text == txt){
document.querySelector("#sel").options[i].selected = true;
break;
}
}
With these codes, the User can select the specific options by entering the name of the product instead of clicking the dropdown list with the mouse and crash the browser.

Redirect to a different page depending on the multiple options selected

I'm hoping someone can help me. I'm creating a form with two questions. Question 1 is where are you located with three different options (New York, California, Maryland) then a second question "What are you eating tonight" with four different options (Lobster, Steak, Crab, Salmon). Based on what the users respond to, they get sent to a unique landing page (each URL will be different). I was able to find this code, but it only works for one dropdown question, whereas I need code that would be good for a unique combination of both dropdowns. I couldn't find this answer anywhere, and I was hoping someone could give me some insight.
<!-- Insert in Settings->Javascript->Header -->
<!-- CS:20200120-11-1 -->
<script>
document.addEventListener("DOMContentLoaded", function() {
function pageGenerator(fieldName) {
return window.__page_generator ? fieldName : base64_encode(fieldName);
}
var dropdownName = "My Dropdown"; // Field name
var options = {
"Option 1": "https://instapage.com", // Each option on a new line
"Option 2": "https://help.instapage.com/hc",
"Option 3": "https://help.instapage.com/hc/en-us/articles/214133067"
// "Option Name" : "Redirect URL if this option is chosen"
}
var selectInput = document.querySelectorAll('form select[name="' + pageGenerator(dropdownName) + '"]');
window.instapageFormSubmitSuccess = function() {
for (var i = 0; i < selectInput.length; i++) {
var selectedOption = selectInput[i].value;
document.querySelectorAll('input[name="redirect"]')[i].value = options[selectedOption];
}
}
});
</script>
<!-- End "Redirect depending on dropdown" || Help center -->```
From what I understood, THIS is a solution that came up with.
CODEPEN link (so that you can execute.)
index.html:
<select id="State">
<option disabled selected> default</option>
<option> NY</option>
<option> CA</option>
<option> MD</option>
</select>
<br><br>
<select id="food" hidden>
<option disabled selected> default</option>
<option> Lobster</option>
<option> Steak</option>
<option> Crab</option>
<option> Salmon</option>
</select>
<script>
let string = ["", ""];
document.getElementById("food").addEventListener("change", event => {
console.log(event);
string[1] = event.target.value;
// document.body.innerText += event.target.value;
window.location.href += "/" + string.join("-");
});
document.getElementById("State").addEventListener("change", event => {
// document.body.innerText += event.target.value;
console.log(event);
string[0] = event.target.value;
document.getElementById("food").hidden = false;
});
Note:
1. You can manipulate the location anyhow you wish by using "window.location.href" I
have used here to continue on the same path.
2. I have kept constant format, that is first the state then " - " and finally food. You can change it to your preference (such as "/state/food" or "/food/state, etc)
3 If you use the codepen then it will redirect to give you an 404 error

small javascript to output options to a select doesnt work

Im making a small webpage. The goal is simple. I have a select with a few options; it is planet names; and their sizes are placed in the value bracket of each option. What i want to do is upon selecting an option ( a planet ), a javascript code will take the choice's size, and give new options to another select bracket. So depending on the first select , the second select bracket will be given new options.
The code is simple and ive overwatched it but theres no error.
I just dont get what's not working. Here's the code:
<select id="selectedplanet" name="selectedplanet" onchange="jcab3();">
<?php
while($fetch28a3=mysqli_fetch_array($query28a3)){
echo('<option value="'.$fetch28a3[1].'">'.$fetch28a3[0].'</option>');
}?>
</select><br/>
<p>Location: </p><br/><br/><p>X:</p><select id="locationx" name="locationX"></select><br/><p>Y:</p><select id="locationy" name="locationY"></select>
This is the html/php side. As you can see , I summon a php that fetch some datas from a mysql table. It assign new options on a select bracket. The select has an 'onchange' , which summon the javascript function 'jcab3' upon changing the select . Then here's the javascript:
function jcab3(){
var final2="";
var final3="";
var prima=parseInt(document.getElementById("selectedplanet").value);
for(i31=0;i31<prima;i31++){
final2=final2+'<option value="'+i31+'">'+i31+'</option>';
}
for(i32=0;i32<prima;i32++){
final3=final3+'<option value="'+i32+'">'+i32+'</option>';
}
document.getElementById("locationx").innerHTML=final2;
document.getElementById("locationy").innerHTML=final3;
}
basically, it takes the size of the planet, then give out new options from 0 to the planet's size , and should place these new options under 2 differents select brackets ( 'locationx' and 'locationy'). But , it just doesnt work.
can anyone help ?
thanks
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="myplanet">
<option value="4">Earth</option>
<option value="5">Mars</option>
<option value="6">JUpiter</option>
</select>
<p>X:</p>
<select id="locationx" name="locationX"></select><br/>
<p>Y:</p>
<select id="locationy" name="locationY"></select>
<script>
document.getElementById("myplanet").addEventListener('change', function(){
var e = document.getElementById("myplanet");
var value = e.options[e.selectedIndex].value;
var prima = parseInt( value )
var final2="";
var final3="";
for(i31=0;i31<prima;i31++){
final2=final2+'<option value="'+i31+'">'+i31+'</option>';
}
for(i32=0;i32<prima;i32++){
final3=final3+'<option value="'+i32+'">'+i32+'</option>';
}
document.getElementById("locationx").innerHTML = final2
document.getElementById("locationy").innerHTML = final3
})
</script>
</body>
</html>
How many new <option>s tags are you adding into your <select>s?
Consider that as saying by #Michael Bogwardt in his comment about what innerHTML is doing in javascript?:
However, DOM manipulations using innerHTML are slower and more
failure-prone than manipulations based on individual DOM objects.
Would be better to create your <option>s tags by using element.appendChild() and element.setAttribute() functions. Your code could look like this:
function jcab3(){
var prima=parseInt(document.getElementById("selectedplanet").value);
var x = document.getElementById("locationx");
var y = document.getElementById("locationy");
for(i31=0;i31<prima;i31++){
var option = x.appendChild("OPTION");
option.setAttribute("value", i31);
}
for(i32=0;i32<prima;i32++){
var option = y.appendChild("OPTION");
option.setAttribute("value", i32);
}
}

JavaScript - dynamic link depending on multiple DropDown Selections or Checkboxes

New to Javascript. Here is the story:
I need to create a dynamic link to redirect to one of the 6 different courses, depending on the options chosen by the user. This can be done via 3 dropdown menus or via 3 sets of checkboxes:
img. 1: http://i.imgur.com/oi8WYYv.png
or
img. 2: http://i.imgur.com/tRIdxBv.png
I tried to combine codes from several examples from stackoverflow, but it's a mess... Any idea is highly appreciated.
[edit 06.04.2015]
Thanks for your suggestions, but the story is a little more complicated:
The links are fixed, i.e. they are quite complicated to write it via a "generate" function (they are something like: base_url + id_1 + base_url_2 + id_2 + base_url_3)
There are 6 different courses, each one with its own link:
a) regular user - in English b) regular user - in German c) user with access to confidential data - in English d) user with access to confidential data - in German e) user manager - in English f) user manager - in German
To select the proper course, you would need to meet criteria from more than one form. I think there should be a lot of "if" statements in place in order to select the proper course via the questions. Or the questions are not the correct ones...
This is fairly trivial; all you have to do is check the values of each select tag, and set the href of the anchor accordingly.
Here's a tiny mockup:
window.onload = function(){
var select = document.getElementById('language');
var anchor = document.getElementById('next');
select.onchange = function(){
anchor.href = select.value;
}
}
Which is your preferred language?
<select id="language">
<option value="#">--------------</option>
<option value="http://stackoverflow.com/questions/tagged/javascript">JavaScript</option>
<option value="http://stackoverflow.com/questions/tagged/python">Python</option>
<option value="http://stackoverflow.com/questions/tagged/c%2b%2b">C++</option>
</select>
<br>
<a id ="next" href="#">Next</a>
Basically, I'm listening to onchange on the select element, and can therefore update the link whenever the chosen option changes.
If you aren't using an <a> anchor tag, but something else, for the Next page button, you can always just check the values before redirecting the user:
window.onload = function(){
var select = document.getElementById('color');
var next = document.getElementById('next');
next.onclick = function(){
switch (select.value){
case '1':
window.location.href = "http://blog.xkcd.com/2010/05/03/color-survey-results/";
break;
case '2':
window.location.href = "http://www.omglasergunspewpewpew.com/";
break;
default:
break;
}
}
}
What is your least favourite colour?
<select id="color">
<option value="1">puke</option>
<option value="2">The best color in the world!</option>
</select><br>
<button id="next">Next</button>
Basically, whatever you're doing, you can just check select.value, and perform an action accordingly.
first draft, not working but that's the best I got so far:
<script type="text/javascript">
window.onload = function(){
var language = document.getElementById('lang');
var confidential = document.getElementById('conf');
var manager = document.getElementById('mgr');
var next = document.getElementById('next');
next.onclick = function(){
switch (true){
case language === "isEnglish":
window.open('link/regular_user_in_English', '_blank');
break;
case language === "isGerman":
window.open('link/regular_user_in_German', '_blank');
break;
case language === "isGerman" && confidential === "isConf":
window.open('link/conf_in_German', '_blank');
break;
default:
break;
}
}
</script>
Which language would you prefer to do the training in?
<select id="lang">
<option value="isEnglish">English</option>
<option value="isGerman">German</option>
</select><br />
Are you a confidential data handler?
<select id="conf">
<option value="notConf">No</option>
<option value="isConf">Yes</option>
</select><br />
Are you a people manager?
<select id="mgr">
<option value="notManager">No</option>
<option value="isManager">Yes</option>
</select>
<br />
<button id="next">Next</button>

Getting a Select Value after appending

This is for javascript and jquery.
I have in my body...
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<script>
$("select").change(function () {
functionLoadOpt2() }).trigger("change" );
</script>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
As we see above, the web page has 2 select boxes and a button. Depending on what you select in the first select box loads what is in the second one, using the functionLoadOpt2 function locating higher up in my code.
if (result == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
...
There is more but it follows the same code different values.
Result is the following, above the if statement(just a row up),
var result = (document.getElementById('option1_select').value);
now on the button click, the function changePage() runs,
and all I want is ...
var result = (document.getElementById('option1_select').value);
var result2= (document.getElementById('option2_select').value);
Assume they selected and option for both. Result2 doesnt work. I'd imagine because I'm appending it but how would I work around this. So that when I click changePage() I get the selected value of option1_select and option2_select.
functionLoadOpt2:
function functionLoadOpt2(){
var opt1Val = (document.getElementById('option1_select').value);
$("#option2_select").find('option').remove().end().append('<option></option>');
if (opt1Val == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
$("#option2_select").append('<option>Letter2</option>');
$("#option2_select").append('<option>Letter3</option>');
$("#option2_select").append('<option>Letter4</option>');
$("#option2_select").append('<option>Letter5</option>');
}else if (opt1Val == "Word2") {
$("#option2_select").append('<option>Letter3</option>');//they have similar ones in some cases
$("#option2_select").append('<option>Letter6</option>');
$("#option2_select").append('<option>Letter7</option>');
$("#option2_select").append('<option>Letter8</option>');
$("#option2_select").append('<option>Letter9</option>');
$("#option2_select").append('<option>Letter10</option>');
$("#option2_select").append('<option>Letter11</option>');
$("#option2_select").append('<option>Letter12</option>');
$("#option2_select").append('<option>Letter13</option>');
$("#option2_select").append('<option>Letter14</option>');
$("#option2_select").append('<option>Letter15</option>');
$("#option2_select").append('<option>Letter16</option>');
$("#option2_select").append('<option>Letter17</option>');
//this works
}
}
use jQuery to get and set the value of <select> with .val()
Both your select elements have the same id, fix it the it should be fine
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
Demo: Fiddle
Note: You can improve the script a lot by using proper jQuery constructs, like this

Categories

Resources