Selection of Items that build a text list HTML - javascript

I am trying to figure out a way so that you could create an online ordering process of a pizzeria (or any restaurant), that is just the example I've picked. The idea is that when clicking on the Option selection, the item selected will fill a text value, adding to the pre-existing list all the selection from the options available.
For example, if I want both a "Viennese" and a "Norcia e Funghi", I would first select Viennese (and it would be in a text), and then select Norcia e Funghi which would be added to the text list after.
That is the best I've come up with (with the help of the Internet, of course), I am trying to improve my skills during the pandemic and I would really appreciate your help! I'm stucked!
<html>
<head>
<script type="text/javascript">
function myNewFunction(element) {
var text = element.options[element.selectedIndex].text;
document.getElementById("test").innerHTML = text;
}
</script>
</head>
<body>
<select id="box1" onChange="myNewFunction(this);">
<option value="1">Nessuna</option>
<option value="2">Viennese</option>
<option value="3">Norcia e Funghi</option>
</select>
<div id="test"></div
</body>
</html>

If I understand you correctly, you want to update the contents of <div id="test"></div> rather than replace each time an item is selected from your list.
<html>
<head>
<script type="text/javascript">
function myNewFunction(element) {
var text = element.options[element.selectedIndex].text;
//Check the items already outputted for the exact text
//Use ... operator to convert into array
var textItems = [...document.getElementById("test").children];
//Filter through the elements to find one that includes matching text
existingItem = textItems.filter(element => element.innerHTML.includes(text));
// If there is an item with the text, then split the text by our seperator and add 1 to it before setting the inner text once more
if (existingItem.length) {
var itemAndQuantity = existingItem[0].innerText.split("-");
var newQuantity = 1 + parseInt(itemAndQuantity[1]);
existingItem[0].innerHTML = itemAndQuantity[0] + " - " + newQuantity;
} else {
//Create a new paragraph element, this could be a <li> instead
var paragraph = document.createElement("p");
//Add a - 1 for the quantity
paragraph.innerHTML = text + " - 1";
document.getElementById("test").appendChild(paragraph);
}
}
</script>
</head>
<body>
<select id="box1" onChange="myNewFunction(this);">
<option value="1">Nessuna</option>
<option value="2">Viennese</option>
<option value="3">Norcia e Funghi</option>
</select>
<div id="test"></div>
</body>
</html>
This will add a new Paragraph element to your div each time an item is selected from the dropdown.

Related

Javascript Syntax getElementById outerHTML

I have a question concerning the Syntax of outerHTML. It is also possible that I am thinking in the wrong direction.
My html file is as follows:
<!DOCTYPE html>
<html lang="en">
<body>
<label for="language">Choose a language:</label>
<select name="language" id="language" value="val1">
<option value="val1">English</option>
<option value="val2">German</option>
</select>
<p>You selected: <span id="language"></span></p> <!-- shall display either "English" or "German" -->
<p>You selected the following option: <span id="language"></span></p> <!-- shall display either "val1" or "val2" -->
<script src="./script.js"></script>
</body>
</html>
I am referring to a script where for the moment the only content is
var selectedlang = document.getElementById("language").outerHTML;
Within the html file it shall show the value and variable for it. I don't know how to proceed.
You can't have more than one element in a document with the same id value; your current markup uses id="language" on three different elements. You'll need to change two of them at least.
I think you're asking how to:
Show the currently-selected option's text and value in the two spans, and
How to update what you show if the user changes the selection.
If you just wanted the selected value, you could use the value property of the select element. But for both text and value, you'll want the selectedIndex property and the options collection:
function showTextAndValue(select, textSpan, valueSpan) {
const option = select.options[select.selectedIndex];
if (option) {
textSpan.textContent = option.text;
valueSpan.textContent = option.value;
} else {
// No option is selected
textSpan.textContent = "";
valueSpan.textContent = "";
}
}
In that example, I've had it accept the select and spans as parameters to the function.
You'd call that function on page load, and then again whenever the select's input event fired.
Here's an example:
const select = document.getElementById("language-select");
const textSpan = document.getElementById("text-span");
const valueSpan = document.getElementById("value-span");
function showTextAndValue(select, textSpan, valueSpan) {
const option = select.options[select.selectedIndex];
if (option) {
textSpan.textContent = option.text;
valueSpan.textContent = option.value;
} else {
// No option is selected
textSpan.textContent = "";
valueSpan.textContent = "";
}
}
// Show on page load
showTextAndValue(select, textSpan, valueSpan);
// Hook the `input` event
select.addEventListener("input", () => {
// Update the contents of the elements
showTextAndValue(select, textSpan, valueSpan);
});
<label for="language">Choose a language:</label>
<select name="language" id="language-select" value="val1">
<option value="val1">English</option>
<option value="val2">German</option>
</select>
<p>You selected: <span id="text-span"></span></p> <!-- shall display either "English" or "German" -->
<p>You selected the following option: <span id="value-span"></span></p> <!-- shall display either "val1" or "val2" -->
<script src="./script.js"></script>
(Note that I changed all three ids.)

How to take user input and add to array in Javascript?

I've got a page im trying to develop which will take user input and then add it to an array and then take that array and make a select and option list out of it as such.
<!DOCTYPE>
<html>
<head>
<script>
var option_list = [];
// for loop at thats option_list to select select tag
for (var i = 0; i < option_list.length; i++){
var opt = option_list[i];
var option = document.createElement("option");
var select = document.getElementById("select");
option.setAttribute("id", opt); //Adding ID to the option list
option.setAttribute("class", "intersect-option"); // adds classes to option
option.value(opt); // adds value to option list
select.appendChild(option); // Adds option to the list.
}
function add_option(name){
var name = document.getElementById("name").value;
name.push(option_list());
}
</script>
</head>
<body>
<input type="text" id="name" value="">
<input type="button" onclick="add_option()" value="add person">
<select id="select">
</select>
</body>
</html>
The issue i am having is that it says when i try and input the information i get back-
Uncaught TypeError: option_list is not a function
at add_option (selectTest.html:19)
at HTMLInputElement.onclick (selectTest.html:25)
I am unsure what i am doing wrong and any help would be greatly appreciated.
You should push name into option_list array. The correct syntax is option_list.push(name);
function add_option(){
var name = document.getElementById("name").value;
option_list.push(name);
}
Pushing elements into array works the other way:
option_list.push(name);
http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
name.push(option_list());
As it says, option_list is not a function, and balanced parentheses after an identifier designate a function call in C family languages, so option_list() is not a valid expression.
Additionally, did you really intend to loop from zero up to the length of an empty array (which is equally zero)?
<!DOCTYPE>
<html>
<head>
</head>
<body>
<input type="text" id="name" value="">
<input type="button" onclick="add_option()" value="add person">
<select id="select">
</select>
<script>
var option_list = [];
// for loop at thats option_list to select select tag
var select = document.getElementById("select");
function add_option(name){
var name = document.getElementById("name").value;
var option = document.createElement("option");
var label = document.createTextNode(name);
option.setAttribute("id", name); //Adding ID to the option list
option.setAttribute("class", "intersect-option"); // adds classes to option
option.value = name; // adds value to option list
option.appendChild(label);
select.appendChild(option); // Adds option to the list.
}
</script>
</body>
</html>

How to get the value of dynamically created dropdown using javascript? And get all values

Here the drop down list is created dynamically.
We are able to get the first value but rest of the value are displayed same as first value.
And we need to concatenate all the values.
When we change the number of conditions it's getting added with the existing one.
Can anyone help me on these? Note: need solution only in JavaScript.
var counter = 1;
var str="";
var con="";
function addInput(divName) {
var count=document.getElementById("ConditionId").value;
for(i=1;i<=count;i++)
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "Condition " + (counter + 0) + " <br><input list='alert' onchange='GetCondition();' id='value'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function GetCondition()
{
str = document.getElementById("value").value;
con=con.concat(str);
alert(con);
}
<html>
<head>
<title>Formatter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form>
<div id="dynamicInput">
Number of Condition:<input type="number" id="ConditionId" onchange="addInput('dynamicInput');">
<br/>
<datalist id='alert'>
<option>Demo 1</option>
<option>Demo 2</option>
<option>Demo 3</option>
<option>Demo 4</option>
<option>Demo 5</option>
<option>Demo 6</option>
</datalist>
</div>
</form>
</body>
</html>
Here i'm getting only the first value right, and other value are same as first value.Need it to change as per the selection.
You can get specific value, if you will know which element you should select.
First of all, in your js function addInput you generating a bunch of inputs with same id. This is bad. Try something like this: ... id='value' + i
Second, I think you should add different identificators to all your options. With specific id you can get all info you want.
OR you can get array of option elements. but then you have to know index of each option

HTML/Javascript issue

I'm having an issue writing some code for a website. It's written in HTML/Javascript. I've managed to write a large chunk of code that seems to work alright, but this issue is now I can't seem to have multiple line strings within Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Multiline test</title>
</head>
<body>
<p>Select variable value below:</p>
<div>
<form name="form001">
<select name="choice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
<p id="selection"></p>
<script type="text/javascript">
// First, get the <select> element. findElementsByName() returns a collection,
// we only want the first elements that's found (hence the [0]):
var choice = document.getElementsByName('choice')[0];
// Now, get a reference to the <p> where we'll show the result:
var selectionP = document.getElementById('selection');
// This Array will hold the labels. label[0] will be 'Text1', labels[1] 'Text2', etc.
var labels = [
"Multiline test \n Multiline test",
"Text2",
"Text3"
];
// Now attach a handler to the onchange event.
// This function will be executed if the <select>ion is changed:
choice.onchange = function() {
var optionIndex = choice.selectedIndex; // The index of the selected option
var text = labels[optionIndex]; // The label that corresponds to that index
selectionP.innerHTML = text;
};
</script>
</body>
This is the updated code. Now all I need is a multiline work around.
This
document.form001.choice
"Text" + choice + "Text"}
Doesn't make any sense, does it? You need to do something like
var choice = document.form001.choice
"Text" + choice + "Text"}
By the way to follow the flow of your JavaScript program you should use Google Chrome's JavaScript Console. It really help understanding what's going on.
i noticed you wrote:
Now what I believe to be happening is that when it's not calling the
Javascript function as it is supposed to.
Inside your function either:
write:
console.log('this function is being executed');
// this will make a line show up in the chrome document inspector / firebug console (just google those)
or
alert('This function is being executed!')
That should help with troubleshooting a lot.
Note: I've put up a working example of this code here: http://jsfiddle.net/F87tJ/
Let's take the following HTML:
<html>
<head></head>
<body>
<p>Select variable value below:</p>
<div>
<form name="form001">
<select name="choice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
<script type="text/javascript">
// JavaScript goes here
</script>
</body>
</html>
Now, I'm going to assume you want to respond to the user changing the selection of the dropdown box. This is pretty easy in JavaScript. Just get a reference to the <select> element and attach an event handler to it. An event handler is just a function that will be called when the given event occurs. In this case:
// First, get the <select> element. findElementsByName() returns a collection,
// we only want the first elements that's found (hence the [0]):
var choice = document.getElementsByName('choice')[0];
// Now attach a handler to the onchange event.
// This function will be executed if the <select>ion is changed:
choice.onchange = function() {
// Do something
};
With me so far? Good.
Now, you wanted to show 'Text1', 'Text2' or 'Text3', based on the selection, right? So, we have to know which <option> is selected. That, too, is easy:
var optionIndex = choice.selectedIndex;
This will just give you a zero-based index of the selected <option>. So, if the first option is selected, optionIndex will have value 0.
To show some text based on the selection, we need some strings. Since we're dealing with a collection here, let's put it in an array:
var labels = [
"Text1",
"Text2",
"Text3"
];
Arrays in JavaScript are also zero-based, so label[0] will be 'Text1', labels[1] 'Text2', etc.
If we bring it all together, we get something like this:
var choice = document.getElementsByName('choice')[0];
var labels = [
"Text1",
"Text2",
"Text3"
];
choice.onchange = function() {
var optionIndex = choice.selectedIndex; // The index of the selected option
var text = labels[optionIndex]; // The label that corresponds to that index
alert(text);
};
I hope this helps. :-)
I rewrote problem areas in your code, and added comments to show what was changed.
<!DOCTYPE html> <!-- HTML pages should have a DOCTYPE header, as well as html, head, and body tags. -->
<html>
<head>
<title></title>
</head>
<body>
Text
Text
Text
Text
<br/>
<br/>
Select variable value below:
<br/>
-
<div>
<form name="form001">
<select name="choice">
<!-- <size=3> Don't think there's a such thing as a size tag -->
<option value=1 selected="selected">1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<script type="text/javascript">
function js001(){ //This was missing paranthesis
var v1 = "Text1"
var v2 = "Text2"
var v3 = "Text3"
var choice = document.form001.choice; //choice wasn't defined
alert("Text" + choice + "Text");
}
</script>
<script type="text/javascript">
//js001();
</script> <!-- The S needed to be lowercase here -->
<div class="pagetext">
<br/>
<br/>
Text
<br/>
<br/>
Text
<div>
</body>
</html>
Here's another version which I think will do what you need.
When the user selects an item from the dropdown, it displays a text string below the dropdown that corresponds to the item that the user selected.
<html>
<body>
<form name="form001">
<!-- when the user changes the selected item in this dropdown, -->
<!-- the JavaScript function "js001()" will get called -->
<select name="choice" onchange="js001()">
<option value=0 selected="selected">1</option>
<option value=1>2</option>
<option value=2>3</option>
</select>
</form>
<!-- This is the div in which the selected item's related text will be shown -->
<div id="selectedStuff"/>
<script type="text/javascript">
function js001()
{
// Rather than use separate variables for each value,
// it is simpler if we store them in an array
var values = ["Text1", "Text2", "Text3"];
// The value of the selected item in the dropdown maps to the index in the values
// array for the text we want to show
var valueIndex = document.form001.choice.value;
var text = "Text" + values[valueIndex] + "Text"
document.getElementById("selectedStuff").innerHTML = text;
}
// When the page loads it makes sense to call the js001() function,
// so that the text for initially-selected dropdown value gets shown
js001();
</script>
</body>
</html>

Show/Hide Div with JavaScript based on Select from Triple Dropdown

Gang -
This is my first time posting. I'm a JavaScript noob - I think I've figured out what direction to take - just not sure how to get there.
I have a triple drop down select menu. I want the third(final) selection to reveal a hidden div. Am I on the right track by thinking I need to use a combination of onchange, getElementById and if statements?
The javascript code for the dropdown is Philip M's Cut & Paste Triple Combo box from JavaScriptKit.com. That work's beautifully. I won't insert my exact code as the category list is significantly longer.
var categories = [];
categories["startList"] = ["Wearing Apparel","Books"]
categories["Wearing Apparel"] = ["Men","Women","Children"];
categories["Books"] = ["Biography","Fiction","Nonfiction"];
categories["Men"] = ["Shirts","Ties","Belts","Hats"];
categories["Women"] = ["Blouses","Skirts","Scarves", "Hats"];
categories["Children"] = ["Shorts", "Socks", "Coats", "Nightwear"];
categories["Biography"] = ["Contemporay","Historical","Other"];
categories["Fiction"] = ["Science Fiction","Romance", "Thrillers", "Crime"];
categories["Nonfiction"] = ["How-To","Travel","Cookbooks", "Old Churches"];
var nLists = 3; // number of select lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms['tripleplay']['List'+i].length = 1;
document.forms['tripleplay']['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue(L3, L2, L1) {
alert("Your selection was:- \n" + L1 + "\n" + L2 + "\n" + L3);
}
function init() {
fillSelect('startList',document.forms['tripleplay']['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
My HTML is:
<div id="menuSearch">
<form name="tripleplay" action="">
<p><select name='List1' onchange="fillSelect(this.value,this.form['List2'])">
<option selected>-- Topic of Interest --</option>
</select></p>
<p><select name='List2' onchange="fillSelect(this.value,this.form['List3'])">
<option selected>-- Geographic Area --</option>
</select></p>
<select id="info"name='List3' onchange="getValue(this.value, this.form['List2'].value, this.form['List1'].value)">
<option selected >-- Information Type --</option>
</select>
</form>
</div>
the divs to show/hide are:
<div id="modelingCV">list of publications</div>
<div id="groundwaterCV">list of publications</div>
<div id="subsidenceCV">list of publications</div>
<div id="managementCV">list of publications</div>
<div id="qualityCV">list of publications</div>
<div id="wildlifeCV">list of publications</div>
Is replacing the getValue in the onchange in the final form select with getElementByID the best approach? And replace the getValue in the javascript function with some type of if statement to specify the values? I am guessing I need to hide the divs with javascript vs CSS? Am I completely off base all around?
Oy. Definitely bit off more than I can chew on this one. Any guidance would be appreciated. Thanks for reading!

Categories