calling dropdown dynamically for selecting date in html - javascript

<select value="dt" name="previousYear">
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option selected="selected" value="2011">2011</option>
<option value="2012">2012</option>
<option value="2012">2013</option>
<option value="2012">2014</option>
</select>
<select value="dt" name="currentYear">
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option selected="selected" value="2011">2011</option>
<option value="2012">2012</option>
<option value="2012">2013</option>
<option value="2012">2014</option>
</select>
<select value="dt" name="nextYear">
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option selected="selected" value="2011">2011</option>
<option value="2012">2012</option>
<option value="2012">2013</option>
<option value="2012">2014</option>
</select>
I have 3 drop down list like this previous year ,current year & next year How can i select the current year as a current year like if the current year is 2012 then it automatically have to select the 2012 when page loads can any one tell me the Javascript code for selecting dynamikcally

Your markup seems incorrect . I guess you are looking for something like this:
<script type="text/javascript">
function setYear()
{
var d = new Date();
var x = document.getElementById("currentYear");//for select box id="currentYear"
x.value=d.getFullYear();
}
</script>
Call it like :
<body onload="setYear()">
<!-- your markup -->
</body>
Call the above function on page load to set current year for the select box.
I would suggest you to learn Javascript for better understanding as its a basic example.Hope this helps.

You should use something as
var d = new Date();
var cur = document.getElementById('currentYear');
var prev = document.getElementById('previousYear');
var next = document.getElementById('nextYear');
var optionC, optionP, optionN;
for (var i = d.getFullYear() - 5; i <= d.getFullYear() + 5; i++) {
optionC = document.createElement("option");
optionC.setAttribute("value", i);
optionC.innerHTML = i;
cur.appendChild(optionC);
}
for (var i = d.getFullYear() - 10; i < d.getFullYear(); i++) {
optionP = document.createElement("option");
optionP.setAttribute("value", i);
optionP.innerHTML = i;
prev.appendChild(optionP);
}
for (var i = d.getFullYear() + 1; i <= d.getFullYear() + 10; i++) {
optionN = document.createElement("option");
optionN.setAttribute("value", i);
optionN.innerHTML = i;
next.appendChild(optionN);
}
cur.value = d.getFullYear();
prev.value = d.getFullYear() - 1;
next.value = d.getFullYear() + 1;​
Just add javascript function like
function setYear(obj)
{
var prev = document.getElementById('previousYear');
var next = document.getElementById('nextYear');
prev.value = Number(obj.value) - 1;
next.value = Number(obj.value) + 1;
}
Updated demo

Related

JavaScript String indexOf() selects also 1&3 instead of only 13

I have this indexOf(), the issue I have is that when norms[] has an dataset like 2,13 that options that are set as selected in norm_id['+nr+'][] are not only the values 2 and 13 but also the values 1 and 3
var element = document.getElementById('norm_id['+nr+'][]');
var values = norms[];
for (var i = 0; i < element.options.length; i++) {
element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}
Any suggestions how to solve this?
I have solved the issue with the code below.
var element = document.getElementById('calc_norm_id['+nr+'][]');
var values = norms;
var values_split = values.split(',');
for (var i = 0; i < element.options.length; i++)
{
for(var j = 0; j < values_split.length; j++)
{
if(element.options[i].value == values_split[j])
{
element.options[i].selected = element.options[i].value;
}
}
}
#Andreas thx for the tip
Looking at your own answer,
element.options[i].selected = element.options[i].value
does not look right to me - You likely mean
element.options[i].selected = true;
which translates the whole if into
element.options[i].selected element.options[i].value == values_split[j];
This is simpler
const norms = "1,13";
const nr = 1;
var values_split = norms.split(',');
var options = document.getElementById('calc_norm_id[' + nr + '][]').options;
[...options].forEach(opt => opt.selected = values_split.indexOf(opt.value) != -1);
<select id="calc_norm_id[1][]" multiple>
<option value="">Please select</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>

Multiple Drop Down Values Won't Display In New HTML Page

Below are my codes which allows user to select multiple values from the drop down list and when the user clicks the button 'Go' the selected values will be displayed on the new page. I've also created classes for both attributes in order to list the selected values.
Unfortunately, when the button is clicked after selections, nothing is being displayed. Need help on this.
"mainTest.html" page.
< script type = "text/javascript" >
(function() {
/**
* Handles the click of the submit button.
*/
function onSubmitClicked(event) {
var url = 'newPageTest.html?';
var foodbevs = document.getElementsByClassName('foodbeverage');
for (var i = 0; i < foodbevs.length; i++) {
if (i > 0) url += '&';
url += 'foodbeverage=' + encodeURIComponent(foodbevs[i].value);
}
var statuses = document.getElementsByClassName('status');
for (i = 0; i < statuses.length; i++) {
url += '&status=' + encodeURIComponent(statuses[i].value);
}
location.href = url;
}
// Get the button from the DOM.
var submitButton = document.getElementById('btngo');
// Add an event listener for the click event.
submitButton.addEventListener('click', onSubmitClicked);
})();
<
/script>
<!DOCTYPE html>
<html>
<body>
<h4 style="color:darkblue">Choose Your Food/Beverage & Quantity : </h4>
<table>
<tr>
<td>
<B>Choose a Food/Beverage : </B>
<select class="foodbeverage">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Food">
<option value = "Chicken Chop">Chicken Chop</option>
<option value = "Pasta">Pasta</option>
<option value = "Pizza">Pizza</option>
<option value = "Chocolate Cake">Chocolate Cake</option>
<option value = "Red Velvet Cake">Red Velvet Cake</option>
<option value = "Ice Cream Cake">Ice Cream Cake</option>
</optgroup>
<optgroup label="Beverages">
<option value = "Milk">Milk</option>
<option value = "Fresh Juice">Fresh Juice</option>
<option value = "Ice Cream">Ice Cream</option>
<option value = "Coffee">Coffee</option>
<option value = "Carbonated Can Drink">Carbonated Can Drink</option>
<option value = "Water">Water</option>
</optgroup>
</select>
<br/>
<B>Choose a Food/Beverage : </B>
<select class="foodbeverage">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Food">
<option value = "Chicken Chop">Chicken Chop</option>
<option value = "Pasta">Pasta</option>
<option value = "Pizza">Pizza</option>
<option value = "Chocolate Cake">Chocolate Cake</option>
<option value = "Red Velvet Cake">Red Velvet Cake</option>
<option value = "Ice Cream Cake">Ice Cream Cake</option>
</optgroup>
<optgroup label="Beverages">
<option value = "Milk">Milk</option>
<option value = "Fresh Juice">Fresh Juice</option>
<option value = "Ice Cream">Ice Cream</option>
<option value = "Coffee">Coffee</option>
<option value = "Carbonated Can Drink">Carbonated Can Drink</option>
<option value = "Water">Water</option>
</optgroup>
</select>
<br/>
</td>
<td>
<B>Dine In or Take Away : </B>
<select class="status">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Status">
<option value = "Dine In">Dine In</option>
<option value = "Take Away">Take Away</option>
</optgroup>
</select>
<br/>
<B>Dine In or Take Away : </B>
<select class="status">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Status">
<option value = "Dine In">Dine In</option>
<option value = "Take Away">Take Away</option>
</optgroup>
</select>
<br/>
</td>
</tr>
</table>
<br/>
<br/>
<input type="submit" id="btngo" value="Go" />
<br/>
</body>
</html>
"newPageTest.html" page.
< script type = "text/javascript" >
function parseQuery(str) {
if (typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {},
first, second;
for (var i = 0; i < s_length; i++) {
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if (first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if (typeof query[first] == "undefined") query[first] = second;
else if (query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
//Function to update "showdata" div with URL Querystring parameter values
function passParameters() {
window.onload = passParameters;
var query = parseQuery(window.location.search);
var data = "<b>Food Beverages:</b> " + query.foodbeverage + " <b>Dine/Takeaway:</b> " + query.status;
document.getElementById("showdata").innerHTML = data;
}
<
/script>
<!DOCTYPE html>
<html>
<body>
<div id="showdata"></div>
</body>
</html>
I find 2 mistake from your code.
Put the window.onload = passParameters; outside of your passParameters function.
For example:
function passParameters() {
var query = parseQuery(window.location.search);
var data = "<b>Food Beverages:</b> " + query.foodbeverage + " <b>Dine/Takeaway:</b> " + query.status;
document.getElementById("showdata").innerHTML = data;
}
window.onload = passParameters;
The parseQuery return {"?foodbeverage":"Chicken Chop","foodbeverage":"Pasta","status":["Dine In","Take Away"]} from input query ?foodbeverage=Chicken%20Chop&foodbeverage=Pasta&status=Dine%20In&status=Take%20Away
You may want to add str = str.substr(1); before var s = str.split("&");
For example
function parseQuery(str) {
if (typeof str != "string" || str.length == 0) return {};
str = str.substr(1);
var s = str.split("&");
var s_length = s.length;
var bit, query = {},
first, second;
for (var i = 0; i < s_length; i++) {
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if (first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if (typeof query[first] == "undefined") query[first] = second;
else if (query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}

loop through associative array in Javascript

Not sure where I am going wrong but the following code seems to list my select option values as 0 - 11 instead of 1 - 12
DYNAMICALLY PRODUCED HTML
<select id="Month" name="month">
<option value="0">January</option>
<option value="1">Feburary</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
JAVASCRIPT
var months = new Array();
months[1] = 'January';
months[2] = 'Feburary';
months[3] = 'March';
months[4] = 'April';
months[5] = 'May';
months[6] = 'June';
months[7] = 'July';
months[8] = 'August';
months[9] = 'September';
months[10] = 'October';
months[11] = 'November';
months[12] = 'December';
for(var i = 0; i<12; i++ ){
month = months[i+1];
option ="<option value='"+i+"'>"+month+"</option>"
options = options+option;
}
$('#month').html(' <select id="' + this.id +'" name="' + this.id + '">'+options+'</select>');
Change this:
option ="<option value='"+(i+1)+"'>"+month+"</option>"
Or better yet:
for(var i = 1; i<=12; i++ )
So change the line
option ="<option value='"+i+"'>"+month+"</option>"
to
option ="<option value='"+(i+1)+"'>"+month+"</option>"
In the for loop you are not increasing the value of i in line 1 (i+1). Therefore the loop goes 0-11. Why don't you just loop with
for (var i = 1; i < 13; ++i){
}

How to dynamically generate a dropdown menu [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my php, I have created two dropdown or selection lists. My drop down list below:
<select name="food">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
<select name="type">
<option value="">--</option>
<option value="Apple">Apple</option>
<option value="Lettuce">Lettuce</option>
<option value="Orange">Orange</option>
<option value="Tomato">Tomato</option>
<option value="Carrots">Carrots</option>
<option value="Mango">Mango</option>
</select>
m one page to the next.
It's possible to do this using jQuery, but it will quickly become unmanageable in a large-scale app or website.
If you go this route, I would avoid using two different select boxes, as this will force you to choose two different names for the form POST, unless you use more jQuery hackery to remedy this problem.
My suggestion is to look at a lightweight JS framework. Knockoutjs has what you need.
Look at this JSFiddle.
var fruitOpts = ["Apple", "Orange", "Mango"];
var vegOpts = ["Lettuce", "Tomato", "Carrots"];
$("#food").change(function () {
var val = $(this).val();
if (val === "") {
return;
}
$("#type").find('option').not(':first').remove().end();
$.each(val === "Fruits" ? fruitOpts : vegOpts, function (i, v) {
$("#type").append("<option value=\"" + v + "\">" + v + "</option>");
});
$.each(val === "Fruits" ? vegOpts : fruitOpts, function (i, v) {
$("#type").append("<option value=\"" + v + "\">" + v + "</option>");
});
});
It's version for two different php pages:
1.php
<script src="1.js"></script>
<a id='link' href='2.php'>go to another page</a>
<select id="food" name="food" onchange="selectFoodType()">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Berries">Berries</option>
</select>
1.js
function selectFoodType()
{
var link = $('#link');
var type = $('select#food option:selected').val();
link.attr('href', link.attr('href') + '?type=' + type);
}
2.php
<script src="2.js"></script>
<select id='type' name="type" data-type='<?=$_GET['type']?>'>
<option value="">--</option>
<option data-type='Fruits' value="Apple">Apple</option>
<option data-type='Vegetables' value="Tomato">Tomato</option>
<option data-type='Vegetables' value="Carrots">Carrots</option>
<option data-type='Berries' value="Strawberry">Strawberry</option>
</select>
2.js
$(function() {
var type = $('select#type').data('type');
var itemsId = document.getElementById("type");
var items = itemsId.getElementsByTagName("option");
var selected_type = [], other_types = [];
selected_type[0] = items[0];
for (var i = 1; i < items.length; i++){
if ($(items[i]).data('type') === type) {
selected_type.push(items[i]);
continue;
}
other_types.push(items[i]);
}
selected_type = selected_type.sort(sortByName);
other_types = other_types.sort(sortByName);
$.merge(selected_type, other_types);
var list = '';
for (i=0; i<selected_type.length; i++) {
list += selected_type[i].outerHTML;
}
$(items).remove();
$(itemsId).append(list);
});
function sortByName(a, b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
return 0;
}
You should assign all Fruits and Vegetables contents in JavaScript object and display related contents of food value in another drop down, see below demo
Food:
<select name="food" id="food">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
Content
<select name="contents" id="contents">
<option value="">...</option>
</select>
JS code
var data = {
'Fruits':['Apple', 'Lettuce', 'Orange', 'Mango'],
'Vegetables': ['Tomato', 'Carrots']
};
document.getElementById("food").onchange = function(Event){
var contents = document.getElementById("contents");
contents.innerHTML = "";
for(var i in data[this.value]){
var option = document.createElement("option");
option.setAttribute('value',data[this.value][i]);
option.text = data[this.value][i];
contents.appendChild(option);
}
var expect_data = Event.target.value == "Fruits" ? "Vegetables" : "Fruits";
for(var i in data[expect_data]){
var option = document.createElement("option");
option.setAttribute('value',data[expect_data][i]);
option.text = data[expect_data][i];
contents.appendChild(option);
}
}
FIDDLE DEMO
you need to use JQuery for this purpose.
See My Solution: http://jsfiddle.net/inventorx/YU4vJ/
Code Here:
HTML
<select name="food" >
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
<select name='type' >
<option>-- Select Food Type --</option>
</select>
<select id='Fruits' style='display:none' >
<option value="">--</option>
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
<option value="Mango">Mango</option>
</select>
<select id='Vegetables' style='display:none' >
<option value="">--</option>
<option value="Lettuce">Lettuce</option>
<option value="Tomato">Tomato</option>
<option value="Carrots">Carrots</option>
</select>
JQUERY
$(document).ready(function(){
$("select[name='food']").on("change", function(){
var value = $(this).val();
$("select[name='type']").html($("#" + value).html());
});
});
Another option.
The list splits into two arrays: food, corresponding to the selected type; and does not correspond to the selected type. Each of these arrays, in turn, is sorted by name:
JSFIDDLE
HTML:
<select id="food" name="food" onchange="selectFoodType()">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Berries">Berries</option>
</select>
<select id='type' name="type">
<option value="">--</option>
<option data-type='Fruits' value="Apple">Apple</option>
<option data-type='Vegetables' value="Lettuce">Lettuce</option>
<option data-type='Vegetables' value="Tomato">Tomato</option>
<option data-type='Berries' value="Strawberry">Strawberry</option>
</select>
JQuery:
function selectFoodType()
{
var type = $('select#food option:selected').val();
var itemsId = document.getElementById("type");
var items = itemsId.getElementsByTagName("option");
var selected_type = [], other_types = [];
selected_type[0] = items[0];
for (var i = 1; i < items.length; i++){
if ($(items[i]).data('type') === type) {
selected_type.push(items[i]);
continue;
}
other_types.push(items[i]);
}
selected_type = selected_type.sort(sortByName);
other_types = other_types.sort(sortByName);
$.merge(selected_type, other_types);
var list = '';
for (i=0; i<selected_type.length; i++) {
list += selected_type[i].outerHTML;
}
$(items).remove();
$(itemsId).append(list);
}
function sortByName(a, b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
return 0;
}

Compose a link based in select's option value

I have 2 dropdown menus, and I need to compose a link with it's values.
Here is the code:
<form id="dropdown1">
<select id="linha">
<option value="G12">Option 1</option>
<option value="G11">Option 2</option>
<option value="H89">Option 3</option>
</select>
<select id="dia">
<option value="all">Every day</option>
<option value="work">working days</option>
<option value="sat">saturday</option>
<option value="sun">sunday</option>
</select>
</form>
I need something in JavaScript to "compose" a link with http://somewebsite.com/*selected_linha_value*/*selected_dia_value*
How can I do that?
<select name="dia" id="dia">
<option value="all">Every day</option>
<option value="http://stackoverflow.com">working days</option>
<option value="http://anotherSite.com">saturday</option>
<option value="http://anotherSite2.com">sunday</option>
</select>
<script>
$("#dia").change(function () {
var selctedValue = "";
$("select option:selected").each(function () {
selctedValue += $(this).val();
window.location.href = selctedValue;
});
});
i think u need something like this.
<script type="text/javascript">
params = getParams();
var name1 = unescape(params["linha"]);
switch(name1)
{
case "g12":
window.location = "http://www.google.com"
}
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
Its not the full code. It will give you some idea. If you have any doubt just comment
Take a look at: http://jsfiddle.net/ERHhA/
You can use jQuery val() to get the value of the select boxes. Then just append these values to the base url.
var url = "http://somewebsite.com/" + $('#linha').val() + "/" + $('#dia').val();
What about this one?
function make_url(){
var linha = document.getElementById('linha').value;
var dia = document.getElementById('dia').value;
var url=window.location.href;
var pos=url.indexOf('?');
if (pos>-1){
url = url.substr(0,pos);
}
//alert(url + '?linha='+linha+'&dia='+dia); return;
document.location.href = url + '?linha='+linha+'&dia='+dia;
}
fiddle
HTML
<div class="container">
<select class="small-nav">
<option value="" selected="selected">Go To</option>
<option value="http://whiterabbitexpress.com">Services</option>
<option value="http://shop.whiterabbitjapan.com">Shop</option>
</div><!-- container -->
JScript:
$(".small-nav").change(function() {
window.location = $(this).find("option:selected").val();
});

Categories