Return Selected Item Value - html

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. :)

Related

Select menu to pass variable to function to change innerhtml

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>

Complicated AJAX update with two select elements

I have a form with two select elements where users can select a product variant (for example red, green, blue shirt) and the quantity.
When changing the variant/quantity, I do a AJAX request to get the price.
The complicated part is: each variation has its own price and its own quantities. For example red shirts are 10 USD and at a minimum quantity of 5 (10, 15…). Green shirts are 15 USD but quantity starts at 3 (6, 9…).
(Color/shirt just an example, real products are control units for streetlights :-)
The problem is, when the default is 'red' and '5' and I change to 'green' the price shows 75 USD (AJAX query was green+5). But green only has quantities of 3, 6, 9 etc.
I could return the minimum quantity from my AJAX request, but then the user can't update the price when changing the quantity select.
Only solution I see is make two doSubmit() functions and two submitAjax(). But this would mean I have a lot of duplicate code.
HTML
<form action="" id="product_selection">
<select name="product_variation">
<option value="r">Red</option>
<option value="g">Green</option>
<option value="b">Blue</option>
</select>
<select name="product_quantity">
<option value="">10</option>
<option value="">20</option>
<option value="">30</option>
</select>
</form>
JavaScript
// Product variation, quantity select dropdown
var product_selection = document.querySelector('#product_selection');
var product_variation = document.querySelector('#product_variation');
var product_quantity = document.querySelector('#product_quantity');
// Event listener to submit the form on change
product_selection.addEventListener('submit', submitAjax);
product_variation.addEventListener('change', doSubmit);
product_quantity.addEventListener('change', doSubmit);
// Submit form
function doSubmit(event) {
product_selection.dispatchEvent(new Event('submit')); // product_selection.submit();
}
// Handle ajax submit
function submitAjax(event) {
// Stop default form submit
event.preventDefault();
// Ajax request
$.ajax({
url: '/static/public/ajax/get_product_data.php',
type: 'POST',
data: $('#product_selection').serialize(),
success: function(result) {
if (result == 0) {
alert('Sorry');
} else {
setProductData(result);
}
},
error: function(jqxhr, status, exception) {
alert('Sorry');
}
})
}
// Update product details
function setProductData(result) {
$('#product_price').html(result.price_gross);
// Remove current quantity options
var product_quantity = document.getElementById("product_quantity");
for(i = product_quantity.options.length - 1 ; i >= 0 ; i--) {
product_quantity.remove(i);
}
// … reapply new quantity options
var c = 0;
for (var i = result.minimum; i <= result.maximum; i+=result.graduation) {
product_quantity.options[c] = new Option(i + ' ' + pwjs.product.unit, i);
if (result.product_quantity == i) {
var setselectedIndex = c;
}
c++;
}
// product_quantity.selectedIndex = setselectedIndex;
}
I think you would want to do this in steps so product_variation.addEventListener('change', doSomethingElse);
then your select would be something like:
<select name="product_variation">
<option data-increment="5" value="r">Red</option>
<option value="g">Green</option>
<option data-increment="3" value="b">Blue</option>
</select>
then when the product_variation changes doSomethingElse would rebuild the product_quantity select to take the increment value of the selected product_variation
As far I can see, you are using jQuery. So, Ill give you an example of how you can achieve this.
HTML
First of all, don't forget to specify the values for your select options, your values for product_quantity were empty. Also, I'd recommend to you that you create an extra option tag to be the default selected option and be able to validate your form later on.
<form action="" id="product_selection" name="product_selection">
<select name="product_variation">
<option value="">Select color</option>
<option value="r">Red</option>
<option value="g">Green</option>
<option value="b">Blue</option>
</select>
<select name="product_quantity">
<option value="">Select quantity</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</form>
JavaScript
As for JavaScript, I'll recommend you to add the event listener for your last input, which is the product_quantity.
$("#product_selection").submit(function(e){
e.preventDefault();
var inputs = document.product_selection;
if( inputs.product_variation.value != "" && inputs.product_quantity.value != "" ){
$.ajax({
url: '/static/public/ajax/get_product_data.php',
type: 'POST',
data: $('#product_selection').serialize(),
success: function(result) {
if (result == 0) {
alert('Sorry');
} else {
setProductData(result);
}
},
error: function(jqxhr, status, exception) {
alert('Sorry');
}
});
}
});

Set selected value of a select that uses Url.Action

I have the following select:
<select id="companiesDDL" class="compDDL tmpdisplay" onchange="location.href=this.value">
#foreach (var item in Model.companyList)
{
<option value='#Url.Action("Writeups", "Writeup", new { symbol = item.SecSymbol, status = "A" })'>#item.SecDesc</option>
}
</select>
This results in a list with options such as
<option value='/Writeup/Writeups?symbol=ssl&status=A'>Sasol Limited-Sponsored - ADR</option>
I want to set the selected value. I tried
$('#companiesDDL option[value="/Writeup/Writeups?symbol=tsla&;status=A"]').prop("selected", true);
but it did not work. How do I do it?

HTML tags to allow user to select multiple items and set their order

I have this input to allow user to select (with multiple choices) a product:
<select multiple="yes" name="products[]">
<option value="wood">Wood</option>
<option value="iron">Iron</option>
<option value="gold">Gold</option>
<option value="dust">Dust</option>
<option value="food">Food</option>
</select>
User can select several stuff in that list, and I can get in server-side using, for instance, PHP:
$_GET['products'] ← array('wood', 'iron', 'food');
Now, I would like to allow users to specify an order for the selection they made. So, I want the user to be able to not only set the list of items to select (like a <select multiple="yes">) but also in which order I will treat them.
In other words, let's say a user want the list to be ordered to:
$_GET['products'] ← array('gold', 'iron', 'wood', 'dust');
Currently, using the <select multiple="yes"> I can only ask user to unorderedly pick up items from a list but
what's the HTML tags I should use to allow user to select multiple options and specify its order?
I don't want to sort the options inside the <select>, I want the user to be able to tell the server in which order it should treat the selected items list.
I picked PHP example as server-side treating code (and it's the language I will use) but actually, the answer should not rely on server side language: I'm looking for the "html-client-side" code to use.
The following answer isn't exactly elegant but it get's the job done. I havn't been doing Web development long but I'm learning.
The JavaScript could be better as I'm used to jQuery (crutch I know).
Pure js (easier if you can use jQuery)
var products = [];
function add(val) {
if (!contains(products, val))
{
products.push(val);
document.getElementById('list').setAttribute('name', products);
}
}
// checks if arr 'a' has the element 'obj'
// thanks to someone at stack overflow for how to do that :)
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
html
// add the onclick='add()' function to your html
<select id='list' multiple="yes" name="" value='heyo'>
<option onclick='add("wood")' value="wood">Wood</option>
<option onClick='add("iron")' value="iron">Iron</option>
<option onClick='add("gold")' value="gold">Gold</option>
<option onClick='add("dust")' value="dust">Dust</option>
<option onClick='add("food")' value="food">Food</option>
</select>
Working jsfiddle here: http://jsfiddle.net/TcGt5/
<!-- language: lang-js -->
<script>
var jproducts = [];
var selectCount= 0;
function myFunction() {
var select = document.getElementById("mySelect");
// test if select value already exist
options = select.getElementsByTagName('option'),
for (var i=options.length; i--;) {
if (options[i].selected)
selectCount +=1;
if (function 'is_not_in_products_array')
jproducts.push(options[i].value)
}
// remove unselected products
for (var j=0; j< (jproducts.length-selectCount); j++;)
jproducts.shift();
}
</script>
Finnaly the products array will containt only the last selected
<select id="myselect" multiple="yes" name="products[]" onchange="myFunction()">
<option value="wood">Wood</option>
<option value="iron">Iron</option>
<option value="gold">Gold</option>
<option value="dust">Dust</option>
<option value="food">Food</option>

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>