Select menu to pass variable to function to change innerhtml - html

I'm making a sidebar page for an add-on in Google Sheets.
The user will select a topic from a select menu (drop down), which will then change the inner html of div to display a different help topic.
So far the variable passed along is what gets displayed. I want the contents of the variable to be displayed as html.
I was able to make this work from text links, but they took up too much space in the sidebar, so I went to a select menu.
I made a simpler sample than my actual help sidebar so there would be less code to look at:
<!DOCTYPE html>
<html>
<body>
<p>Select a choice from the list.</p>
<select id="topic" onchange="showContent(this.value)">
<option value="choice1">This one</option>
<option value="choice2">the next one</option>
<option value="choice3">Yet another</option>
</select>
<p>When you select a choice, the output should change based on the value of the variable passed.</p>
<p id="helpContent">Results go here</p>
<script>
//VARS
var choice1 = '<ul><li>This is the first choice<li></ul>';
var choice2 = '<ul><li>This is the second choice<li></ul>';
var choice3 = '<ul><li>This is the, like, third choice<li></ul>';
function showContent(topic) {
document.getElementById("helpContent").innerHTML = topic;
}
</script>
</body>
</html>

Use a data structure to represent your elements, and then create them accordingly
<!DOCTYPE html>
<html>
<body>
<p>Select a choice from the list.</p>
<select id="topic" onchange="showContent(this.value)">
<option value="choice1">This one</option>
<option value="choice2">the next one</option>
<option value="choice3">Yet another</option>
</select>
<p>When you select a choice, the output should change based on the value of the variable passed.</p>
<p id="helpContent">Results go here</p>
<script>
var choices = {
"choice1": {
list: ["item1", "item2", "item3"]
},
"choice2": {
list: ["item1"]
},
"choice3": {
list: ["item3"]
},
}
function showContent(topic) {
var currentChoice = choices[topic];
if (currentChoice == null)
return alert("Invalid choice");
var newList = document.createElement('ul');
for (var i = 0; i < currentChoice.list.length; i++) {
var newListItem = document.createElement('li');
newListItem.innerText = currentChoice.list[i];
newList.appendChild(newListItem);
}
var sidebarContainer = document.getElementById("helpContent");
sidebarContainer.innerHTML = "";
sidebarContainer.appendChild(newList);
}
window.onload = function() {
showContent("choice1");
}
</script>
</body>
</html>

Related

HTML datalist array

Please help me change path of the code so that the drop-down list changes when adding new elements to the array. I’ve been fighting this problem for half a day.Now I have to add manually each time. I tried to find the answer at SO, but all my attempts to change part of the code turned out to be a failure. It seems to me that I still do not understand the logic of HTML Thank you in advance!
js code part:
t.DropdownList = (values); // loading every time before html starts
HTML code part:
<div class="demo" >
<style type="text/css"> .demo { margin: 30px ; color : grey ; font-family :
arial sans-serif ;font-size : 10pt }
o { color : red ; font-size : 14pt }
r { color : gray ; font-size : 14pt }
</style>
<h1>Передача клиента:</h1> <br>
<h1><?= ClientName ?></h1> <br>
<r>Адрес:</r>
<r><?= ClientAdress ?></r> <br>
<r>Менеджер клиента:</r>
<o><?= Manager ?></o> <br>
<br>
<form id='myForm'>
<label for="managers-choice">Выберите менеджера для передачи клиента:</label>
<input list="managers" id="dropdownlist" name="dropdownlist" />
<input
onclick="google.script.run.Message02(document.getElementById('myForm'));myFuncti on();this.disabled=true" type="button" value="Передать" />
</form>
<datalist id="managers">
<option value =<?=DropdownList[0]?> > // in this place I need help, because if the next load the array is shorter, then I will get an undefined result.
<option value =<?=DropdownList[1]?> >
<option value =<?=DropdownList[2]?> >
<option value =<?=DropdownList[3]?> >
<option value =<?=DropdownList[4]?> >
<option value =<?=DropdownList[5]?> >
</datalist>
<script>
$('#dropdownlist').datepicker({ dateFormat: 'dd.mm.yy' });
function myFunction() {
var b = document.getElementById('result');
b.innerHTML = 'Менеджер выбран.';
document.getElementById('dropdownlist').disabled = 'disabled';
//alert('The output has been modified');
return;
}
</script>
<body>
<div id="result">Вы еще не выбрали менеджера.</div>
</body>
</div>
Here's how I do it:
JavaScript:
$(function(){
google.script.run
.withSuccessHandler(function(rObj){
grObj=rObj;
updateSelect(grObj.mnA);
})
.getRecipeList1();//google apps script function on server
});
function updateSelect(vA,id){
var id=id || 'sel1';
var select = document.getElementById(id);
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i],i);
}
}
So it always gets the latest list every time the page is loaded.

Return Selected Item Value

So I have this select block in my code:
<select id="mS" name="mealSelection" onselect="">
<optgroup label="Generell">
<option selected label="Alles" value="0" />
</optgroup>
#{
List<List<string>> kategorien = new List<List<string>>();
List<List<int>> catIDs = new List<List<int>>();
while (reader.Read())
{
if (reader["TopKategorie"].ToString().Equals(""))
{
List<string> nextList = new List<string>();
nextList.Add(reader["Bezeichnung"].ToString());
kategorien.Add(nextList);
List<int> nextCatList = new List<int>();
nextCatList.Add(Int32.Parse(reader["ID"].ToString()));
catIDs.Add(nextCatList);
}
else
{
int lastPos = kategorien.Count - 1;
kategorien[lastPos].Add(reader["Bezeichnung"].ToString());
catIDs[lastPos].Add(Int32.Parse(reader["ID"].ToString()));
}
}
for (int i = 0; i < kategorien.Count; i++)
{
<optgroup label=#kategorien[i][0]>
#for (int j = 1; j < kategorien[i].Count; j++)
{
<option label=#kategorien[i][j] value=#catIDs[i][j] />
}
</optgroup>
}
}
</select>
Short explanation: Our professor gave us the task to create a web application in which you can order food. This list is meant to filter the food by category (e.g. Asian, fast food etc.) I used a two dimensional List, because the categories are all separated in "top-categories" like snack, dessert, and so on.
I now need a button that links to a url containing the value of the selected option as parameter. However, my professor specifically demanded to use "select", "optgroup" and "option" and I haven't worked with controllers yet. Any help is appreciated.
Just use a script to get the new value. Because you getting it on the fly it will have to be a client side language. (Like Jquery or Javascript)
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
<script>
function myFunction() {
var selected-val = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + selected-val;
}
</script>
Once you have the value you can do whatever it is you want to do with the info. :)

How can I display option text on the dropdown menu that is different than the selected text?

Using a simple select, I want to display one text on the dropdown list and another text in the select control after the option was selected. It's pretty similar to option's label attribute in its concept.
I'm not sure if it's even possible. Here's a not-working example:
<select>
<option select-text="-- EMPTY --"> </option>
<option select-text="YES!!!">Yes</option>
<option>No</option>
</select>
Update: I didn't mention that I need to incorporate this solution in a generated HTML (ng-table filters), so any solution that is not pure HTML will be very hard to use. I even consider to look for another table control as a simpler solution, which is pretty basic - placeholder text in select filter.
I've created a question more specific to my problem:How can I put a placeholder text on ng-table select filter?
Here's a relatively simple solution that relies on the standard value attribute and a custom data-* attribute:
function showDisplayValue(e) {
var options = e.target.options,
option = e.target.selectedOptions[0],
i;
// reset options
for (i = 0; i < options.length; ++i) {
options[i].innerText = options[i].value;
}
// change the selected option's text to its `data-display` attribute value
option.innerText = option.getAttribute('data-display');
}
document.getElementById('foo').addEventListener('change', showDisplayValue, false);
<select id="foo">
<option data-display="*** BAR ***" value="Bar">Bar</option>
<option data-display="*** BAZ ***" value="Baz">Baz</option>
<option data-display="*** QUX ***" value="Qux">Qux</option>
</select>
Found something similar to what you're asking for here:
https://stackoverflow.com/a/19184179/6555780
It basically needs to be organised in javascript, so that the selected option shows immediately on the screen, the below code was taken from David's answer and can be viewed here: http://jsfiddle.net/aCb73/
<select name="ref_rubrique" id="ref_rubrique">
<option value="-- EMPTY --" selected> </option>
<option value="YES!!!">Yes</option>
</select>
<div id="ref_output"></div>
<script type="text/javascript">
var selectElement = document.getElementById('ref_rubrique');
var divElement = document.getElementById('ref_output');
selectElement.onchange = function () {
var selectedValue = selectElement.options[selectElement.selectedIndex].value;
if (selectedValue == '-- EMPTY --') {
divElement.innerHTML = '<p>No</p>';
} else if (selectedValue == 'YES!!!') {
divElement.innerHTML = '<p>Yes</p>';
}
};
</script>
This basically targets the ref_rubique select tag and displays the code in the Javascript based on the selection (defaults as --EMPTY--)
Following our comments below, the following code could possibly help with ng-table:
self.initialSorting = [
{ label: "Id ASC", value: { id: "asc"} },
{ label: "Id DESC", value: { id: "desc"} },
{ label: "Name ASC", value: { name: "asc"} },
{ label: "Name DESC", value: { name: "desc"} }
];
What I understand is you want to print the text in select-text attribute.
I've found this example if this is what you are looking for.
<select id="mySelect">
<option select-text="-- EMPTY --"> </option>
<option select-text="YES!!!">Yes</option>
<option>No</option>
</select>
$("#mySelect").change(function(){
$("#mySelect option:selected").text($("#mySelect").val());
});
This is where I found something similar.
HTML select shows value instead of text

Drop-down lists with the same content in HTML

Hello, community. Is it possible to specify a drop-down list structure at one place and to use it for several drop-down lists? For example, I need 5 drop-down lists all comprising 3 entries: "Basic", "Advanced", "Professional". Do I really need to write the following 5 times?
<select id="myid" name="myname" size="1">
<option value="1">Basic</option>
<option value="2">Advanced</option>
<option value="3">Professional</option>
</select>
BR
Ewgenij
I have done something similar recently.
It is simple. Look at my code below which I used to automatically enter dates for a select dropdown:
<select id="dateDropdown"></select> /*give an id for select*/
<script type="text/javascript">
var dateSelectId = document.getElementById("dateDropdown"); /*get the select element by its id*/
for (var i = 0; i < 8 ; i++) { /*for loop to create the options - in my case 8 options */
var currentDate = moment().subtract('d',i).format("MMM D"); /*ignore this - it basically just gives different dates for me*/
var paramObj = { /*declaring an obj for the 'option' tag's parameters*/
'optValue':i, /*value for the 'option' tag*/
'optText':currentDate /*text for 'option' tag*/
};
optionGenerator(dateSelectId,paramObj); /*function which actually creates <option> tags and assigns the parameters to it*/
};
Below is my javascript file which I import which contains the optionGenerator() function
/*Function to dynamically create select list and adding options to it*/
var optionGenerator = function(selectId,paramObj){
var optionInstance = document.createElement("option"); //creates child <option> element
optionInstance.value = paramObj.optValue;
optionInstance.text = paramObj.optText;
selectId.options.add(optionInstance); //adds the <option> tag with desired values
};
Let me know if you understood.
With php you can do like this
$select_box = "<select id='myid' name='myname' size='1'>
<option value='1'>Basic</option>
<option value='2'>Advanced</option>
<option value='3'>Professional</option>
</select>";
echo $select_box ;// where-ever you want in between your HTML tags
?>
eg,
<form >
<?php echo $select_box ; ?>
...other inputs...
</form>

implementing select and deselect (toggle) on a SELECT TAG

The current HTML SELECT tag works great for me except for one thing. Is it possible to implement toggling on the current item.
If I have a current selection, I'd like to click it again and "de-select" it. It doesn't work that way now, it simply keeps the current selection "selected".
It seems that I need to know the "previous" selection along with the "current" selection and compare the 2 to see if I need to "de-select" everything. How do I get the previous selection, all I know about is "selectedIndex" which is the current selection.
Is there a way?
To accomplish this you might use a little bit of javascript as follows. I have tested and it seems to work as you requested. I am being verbose for readability, but you can clean once you have it working for you.
<script language="JavaScript" type="text/javascript">
function toggleSelectedValue() {
var selObj = document.getElementById('myList');
var selIndex = selObj.selectedIndex;
var selValue = selObj.options[selIndex].value;
var prevSelValue = document.getElementById('trackSelectedValueHiddenField').value;
if (selValue == prevSelValue) {
//Delect "all" items
selObj.selectedIndex = -1;
document.getElementById('trackSelectedValueHiddenField').value = 0;
}
else {setSelectedValue();}
}
function setSelectedValue()
{
var selObj = document.getElementById('myList');
var selIndex = selObj.selectedIndex;
document.getElementById('trackSelectedValueHiddenField').value = selObj.options[selIndex].value;
}
</script>
</head>
<body>
<div id="wrapper">
<div id="contentDiv" style="height:686px; border: solid 1px red;">
<select multiple="multiple" id="myList" onclick="toggleSelectedValue()">
<option value="1">Test</option>
<option value="2">Test</option>
<option value="3">Test</option>
</select>
<input type="hidden" id="trackSelectedValueHiddenField" value="0" />
</div>
</div>
</body>
</html>