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>
Related
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.
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
So, what I'm trying to do here is make a clicker game. I want the enemy to be selectable from a dropdown list, and then you can click whichever enemy you select to add to your resources (of which there are four for this game). However, when I use this code, the clickable images won't show up. Is there a more efficient way to do this? Here's the HTML and the Javascript from the sections I'm working on (the other sections have already been tested to see that they work). The images it's referring to are in the same folder and the onclick functions have already been written, and were tested with a non-dropdown list image and worked. The dropdown list worked for a non-clickable image. They just don't seem to work when I put them together.
function changeE(){
var dropdownList = document.getElementById('changeEid');
var selectedIndex = dropdownList.selectedIndex;
var selectedValue = dropdownList.options[selectedIndex].value;
var enemyDiv = document.getElementById('enemyHere');
switch(selectedValue){
case 'DestroyerPrincess':
enemydiv.innerHTML = '<img src="B1-DestroyerPrincess.png" width="445px" height="590px" onclick="fuelClick(1);ammoClick(1); steelClick(1); bauxiteClick(1)">';
break;
case 'LightCruiserDemon':
enemydiv.innerHTML = '<img src="B2-LightCruiserDemon.png" width="424px" height="616px" onclick="fuelClick(1);ammoClick(1); steelClick(1); bauxiteClick(1)">';
break;
}
};
Enemy
<select id="changeEid" onclick="javascript:changeE();">
<option value="DestroyerPrincess">Destroyer Princess</option>
<option value="LightCruiserDemon">Light Cruiser Demon</option>
</select>
<div id="enemyHere">
</div>
It's simply a typo. In JavaScript part of code, replace enemydiv.innerHTML by enemyDiv.innerHTML
function changeE(){
var dropdownList = document.getElementById('changeEid');
var selectedIndex = dropdownList.selectedIndex;
var selectedValue = dropdownList.options[selectedIndex].value;
var enemyDiv = document.getElementById('enemyHere');
switch(selectedValue){
case 'DestroyerPrincess':
enemyDiv.innerHTML = '<img src="B1-DestroyerPrincess.png" width="445px" height="590px" onclick="fuelClick(1);ammoClick(1); steelClick(1); bauxiteClick(1)">';
break;
case 'LightCruiserDemon':
enemyDiv.innerHTML = '<img src="B2-LightCruiserDemon.png" width="424px" height="616px" onclick="fuelClick(1);ammoClick(1); steelClick(1); bauxiteClick(1)">';
break;
}
};
Instead of onclick i suggest you to use onchange event:
<select id="changeEid" onchange="javascript:changeE();">
<option value="DestroyerPrincess">Destroyer Princess</option>
<option value="LightCruiserDemon">Light Cruiser Demon</option>
</select>
with select tags i always use onchange it's better because you only want changes to be made when the user selects something it does make sense , i hope this helps
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.
I have a selectbox with a couple of options in it. When an option is selected, the Javascript code gets the value of the selected option and has to change the font of a text accordingly.
I figured I would use the Switch-Case statement because I have multiple options, but it doesn't seem to work, nothing changes.
Javascript
function font() {
var sf = document.getElementById('box').value;
var generate = document.getElementById('generate');
switch (sf) {
case 'TimesNewRoman':
generate.style.fontFamily('Times New Roman')
break;
case 'Georgia':
generate.style.fontFamily('Georgia')
break;
case 'PalatinoLinotype':
generate.style.fontFamily('Palatino Linotype')
break;
default:
generate.style.fontFamily('Arial')
}
}
HTML
<select id="box" onchange="font();">
<option id="TNR" value="TimesNewRoman">Times New Roman</option>
<option id="GRG" value="Georgia">Georgia</option>
<option id="PLT" value="PalatinoLinotype">Palatino Linotype</option>
</select>
<br />
<div id="generate">This is some text</div>
NOTE
I have more options in the list but I have shorten it for the sake of simplicity.
Am I wrong for using this statement, or am I missing something entirely?
You haven't made an assignment, use generate.style.fontFamily = "Arial";