This is my dropdown in html
<select name="select" class="form-control" id="dropdownYear" style="width: 120px;" onchange="getProjectReportFunc()">
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017" selected="selected">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
I have hard coded the year values, i want to populate this dropdown
with current year selected and 3 years before and after that.Eg for
current year=2017 i want the list to be 2013-2020 with 2017
automatically selected. How do i do this in js?
To achieve this, using Date is required, be it directly or with some external library. With the native method getFullYear:
Date.prototype.getFullYear()
Returns the year (4 digits for 4-digit years) of the specified date according to local time.
We can set the current year and then loop through desired values. You specified 2013 - 2020, so we'll use the current year minus 4 up to the current year plus 3.
for (var i = year - 4; i <= year + 3; i++)
In the body of the loop, create Options and add them to the Select. To display the values, the innerHTML needs to be set, and if you want to use the value somewhere else in your javascript, the value also needs to be set:
option.value = option.innerHTML = i;
If the index equals the current year, set the selected attribute.
if (i === year) option.selected = true;
Then, all you need to do is append each option element to the select element. After the select has been created, insert it into your HTML (here I am appending to the body).
var select = document.createElement('select');
var date = new Date();
var year = date.getFullYear();
for (var i = year - 4; i <= year + 3; i++) {
var option = document.createElement('option');
option.value = option.innerHTML = i;
if (i === year) option.selected = true;
select.appendChild(option);
}
document.body.appendChild(select);
You may try something like this :
$('#dropdownYear').each(function() {
var year = (new Date()).getFullYear();
var current = year;
year -= 3;
for (var i = 0; i < 6; i++) {
if ((year+i) == current)
$(this).append('<option selected value="' + (year + i) + '">' + (year + i) + '</option>');
else
$(this).append('<option value="' + (year + i) + '">' + (year + i) + '</option>');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="select" class="form-control" id="dropdownYear" style="width: 120px;" onchange="getProjectReportFunc()">
</select>
var i, currentYear, startYear, endYear, newOption, dropdownYear;
dropdownYear = document.getElementById("dropdownYear");
currentYear = (new Date()).getFullYear();
startYear = currentYear - 4;
endYear = currentYear + 3;
for (i=startYear;i<=endYear;i++) {
newOption = document.createElement("option");
newOption.value = i;
newOption.label = i;
if (i == currentYear) {
newOption.selected = true;
}
dropdownYear.appendChild(newOption);
}
<select name="select" class="form-control" id="dropdownYear"
style="width: 120px;" onchange="getProjectReportFunc()">
</select>
This is very simple logic,
First get current year,
Then run loop starting from currentyear -2 to currenct year + 3
Make current year selected
See code below:
console.clear();
var curYear = new Date().getFullYear();
for(i = curYear-2 ; i <= curYear+3 ; i++) {
var selected = (curYear === i) ? 'selected="selected"': '';
console.log('<option '+selected+' value="'+i+'">'+i+'</option>');
}
You can use ES6 array features.
let currentYear=new Date().getFullYear();
let array=Array.from(Array(7), (_, i) => currentYear-3+i);
array.forEach(function(item){
let option=$('<option></option>').html(item).attr('selected', item == currentYear);
$('select').append(option);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="select" class="form-control" id="dropdownYear">
</select>
A simple example, without using JQuery -
var currentYear = new Date().getFullYear();
var yearSelect = document.getElementById('dropdownYear');
for(var i = -2; i < 3; i++) {
var isSelected = currentYear === currentYear - i
yearSelect.options[yearSelect.options.length] = new Option(currentYear - i, currentYear - i, isSelected, isSelected);
}
and the HTML:
<select name="select" class="form-control" id="dropdownYear" style="width: 120px;" onchange="getProjectReportFunc()" />
HTML:
<select
name="select"
class="form-control"
id="dropdownYear"
style="width: 120px;"
onchange="getProjectReportFunc()">
</select>
Javascript:
let select = document.getElementById('dropdownYear');
let currYear = new Date().getFullYear();
let futureYear = currYear+3;
let pastYear = currYear-3;
for(let year = pastYear; year <= futureYear; year++){
let option = document.createElement('option');
option.setAttribute('value', year);
if(year === currYear){
option.setAttribute('selected', true);
}
option.innerHTML = year;
select.appendChild(option);
}
While I appreciated a lot of these answers, I felt like these could and should be done using the modern tools .map and Array constructor, so I created the below:
const CreateYearDropdown = () => {
const nYearsPrior = 20;
const nYearsPost = 20;
const yearRange = Array(nYearsPrior+nYearsPost).fill(0);
const currentYear = new Date().getFullYear();
const years = yearRange.map(
(item, index) => (item[index] = currentYear - nYearsPrior + index)
);
return (
<select defaultValue={currentYear}>
{years.map((year, index) => (
<option key={index} value={year}>
{String(year)}
</option>
))}
</select>
)
}
Without the above explanation/breakdown, it can be written like so:
const CreateYearDropdown = () => {
const currentYear = new Date().getFullYear();
const yearRange = Array(40).fill(0);
const years = yearRange.map(
(item, index) => (item[index] = currentYear - 20 + index)
);
return (
<select defaultValue={currentYear}>
{years.map((year, index) => (
<option key={index} value={year}>
{year}
</option>
))}
</select>
);
};
Alternatively you can have it running in a single direction (before or after):
const CreateYearDropdown = () => {
const currentYear = new Date().getFullYear();
const yearRange = Array(20).fill(0);
const years = yearRange.map(
(item, index) => (item[index] = currentYear /* - or + */ + index)
);
return (
<select defaultValue={currentYear}>
{years.map((year, index) => (
<option key={index} value={year}>
{year}
</option>
))}
</select>
);
};
Related
Good morning!
I have a page with 1 dropdown menu that has 24 options to select.
As well There are 12 checkboxes to select.
Each dropdown option and each checkbox has a predefined variable.
i.e.:
dropdown value="utcValue0 -> var utc0 and
checkbox value id="gameCheck" -> var gameTag
desired output here is a new variable var a = utc0 + gameTag;
My current solution works, however it is very tedious and terrible to read and there must be a whole lot easier way to handle this. I'm at the moment just defining each scenario 1 by 1.
Considering it's 24 dropdown menus and 12 checkboxes this can not be the way..
I think it can be done with a smart nested loop, but I can't come up with how to actually write that.
I'd highly appreciate some help! Thank you so much!
<select name="hourSelector" id="hourSelectorID">
<option value="utcValue0">0 - 1 UTC</option>
<option value="utcValue1">1 - 2 UTC</option>
<option value="utcValue2">2 - 3 UTC</option>
<option value="utcValue3">3 - 4 UTC</option>
<option value="utcValue4">4 - 5 UTC</option>
<option value="utcValue5">5 - 6 UTC</option>
</select>
<input type="checkbox" class="custom-control-input" id="gameCheck">
<input type="checkbox" class="custom-control-input" id="purchCheck">
<input type="checkbox" class="custom-control-input" id="inputCheck">
var utc0 = 'something';
var utc1 = 'something';
var utc2 = 'something';
var utc3 = 'something';
var utc4 = 'something';
var utc5 = 'something';
//var utcX = 'created>"' + todayUTC + 'T00:00:00Z"' + ' ' + 'created<"' + todayUTC + 'T01:00:00Z"';
var gameTag = 'whatever';
var purchTag = 'otherwhatever';
var eventTag = 'morewhatver';
// grab input Hour
var hourDropdown = document.getElementById("hourSelectorID");
var selectedHour = hourDropdown.options[hourDropdown.selectedIndex].value;
if (document.getElementById('gameCheck').checked) {
if (selectedHour == 'utcValue0' ) {
var a = utc0 + eventTag
}
if (selectedHour == 'utcValue1') {
var a = utc1 + eventTag
}
if (selectedHour == 'utcValue2') {
var a = utc2 + eventTag
}
if (selectedHour == 'utcValue3') {
var a = utc3 + eventTag
}
if (selectedHour == 'utcValue4') {
var a = utc4 + eventTag
}
if (selectedHour == 'utcValue5') {
var a = utc5 + eventTag
}
}
You have changed your question so I'm not sure with what follows. Drop a comment below for adjustments or questions :-)
var formEl = document.getElementById("form");
var selectEl = document.getElementById("hourSelectorID");
var checkboxEls = Array.prototype.slice.call(
document.getElementsByClassName("custom-control-input")
);
// option elements
for (let i = 0; i < 24; i++) {
let optionEl = document.createElement("option");
optionEl.value = "utcValue" + i;
optionEl.textContent = i + " - " + (i + 1) + " UTC";
selectEl.appendChild(optionEl);
}
// form submit
formEl.addEventListener("submit", function (ev) {
ev.preventDefault();
console.log(toStringStuff());
});
// rename as needed :-)
function toStringStuff () {
var now = Date.now(); // in ms
var hourInMs = 1000 * 60 * 60;
var dayInMs = hourInMs * 24;
var today = now - now % dayInMs; // `now` with time set to 0
var i = selectEl.selectedIndex; // hours to add to `today`
var dt0 = new Date(today + i * hourInMs).toISOString();
var dt1 = new Date(today + (i + 1) * hourInMs).toISOString();
var utc = 'created>"' + dt0 + ' ' + 'created<"' + dt1;
return [utc].concat(checkboxEls.filter(
function (el) { return el.checked; }
).map(
function (el) { return el.value; }
)).join(" ");
}
<form id="form">
<select
id="hourSelectorID"
name="hourSelector"
></select>
<label><input
id="gameCheck"
type="checkbox"
class="custom-control-input"
value="gameTag"
checked
> Game Check</label>
<label><input
id="purchCheck"
type="checkbox"
class="custom-control-input"
value="purchTag"
checked
> Purch Check</label>
<input type="submit">
</form>
Here is a solution taking advantage of the options indexes matching the itteration of the string. It takes the index of the selected option and changes the string accordingly while concatenating the values from selected checkboxes.
let dateUTC = new Date();
let todayUTC = dateUTC.getUTCFullYear() + '-' + (('0' + dateUTC.getUTCMonth()+1)).slice(-2) + '-' + ('0' + dateUTC.getUTCDate()).slice(-2);
const select = document.querySelector("#hourSelectorID");
const allCheckboxes = document.querySelectorAll('input[name="chkBox"]');
const elements = [...allCheckboxes, select]
elements.forEach(el => {
el.addEventListener("change", () => {
let checkedValues = []
const checked = [...allCheckboxes].filter(cb => cb.checked);
checked.forEach(cb => checkedValues.push(cb.value))
console.log(`created>" ${todayUTC} T0${select.selectedIndex}:00:00Z" created<" ${todayUTC} T0${select.selectedIndex+1}:00:00Z" ${checkedValues.join(' ')}`)
});
});
<select name="hourSelector" id="hourSelectorID">
<option value="utcValue0">0 - 1 UTC</option>
<option value="utcValue1">1 - 2 UTC</option>
<option value="utcValue2">2 - 3 UTC</option>
<option value="utcValue3">3 - 4 UTC</option>
<option value="utcValue4">4 - 5 UTC</option>
<option value="utcValue5">5 - 6 UTC</option>
</select>
<input value="whatever" type="checkbox" name="chkBox" class="custom-control-input" id="gameCheck">
<input value="otherwhatever" type="checkbox" name="chkBox" class="custom-control-input" id="purchCheck">
<input value="morewhatver" type="checkbox" name="chkBox" class="custom-control-input" id="inputCheck">
I have the selectbox with the option 2019-2020,2020-2021.I I choose the financial year 2019-2020 I want to display the month as {"month":["Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar"]}.
If I choose the financial year 2020-2021 I want to display the month {"month":["Apr","May"]}.
Is it possible to get the json based on selected financial year. can I get the json response in select option onclick
$('.financialyear').change(function(){
console.log($('.financialyear').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="financialyear" >
<option>2019-2020</option>
<option>2020-2021</option>
</select>
Try following code:
var months = [ "Jan","Feb","Mar", "Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" ];
var starting_month = "Apr";
var current_year = new Date().getFullYear().toString();
var current_month = months[ new Date().getMonth() ];
$('.financialyear').change(function(){
console.clear();
var value = $('.financialyear').val();
var start_year = value.split('-')[0];
var index = months.indexOf( starting_month );
var count = 0;
var financial_months = [];
while( count < 12 ) {
financial_months.push( months[index] );
if ( current_year === start_year && current_month === months[index] ) {
break;
}
index++;
if ( index === months.length ) {
index = 0;
}
count++;
}
console.log( { months: financial_months } );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="financialyear" >
<option value="2019-2020">2019-2020</option>
<option value="2020-2021">2020-2021</option>
</select>
I have one dropdown and two textbox on my page. Now i have to bind the value
based on dropdown value.
My question is when i am select This Week from dropdown that time it will
display wrong date when first date of month on second textbox.
Look at the below example. It is working fine on other date of month but when
select '07/01/2017' then it's display like this '01/06/2017' rather then
'01/07/2017' on second textbox when we select This Week.
$(document).on("change","#selectDates",function() {
var dropValue = document.getElementById('selectDates').value;
//All
if (dropValue == "1") {
$('#txtDateFrom').val('');
$('#txtDateTo').val('');
}
//Today
else if (dropValue == "2") {
var back_GTM = new Date();
$('#txtDateFrom').val(Back_date(back_GTM));
$('#txtDateTo').val(Back_date(back_GTM));
}
//This Week
else if (dropValue == "3") {
//var curr = new Date; // get current date
var curr = new Date('07/01/2017'); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first));
var lastday = new Date(curr.setDate(last));
$('#txtDateFrom').val(Back_date(firstday));
$('#txtDateTo').val(Back_date(lastday));
}
});
function Back_date(back_GTM) {
var b_dd = back_GTM.getDate();
var b_mm = back_GTM.getMonth() + 1;
var b_yyyy = back_GTM.getFullYear();
if (b_dd < 10) {
b_dd = '0' + b_dd
}
if (b_mm < 10) {
b_mm = '0' + b_mm
}
return back_date = b_dd + '/' + b_mm + '/' + b_yyyy;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-style">
<select id="selectDates">
<option value="1" selected>All</option>
<option value="2">Today</option>
<option value="3">This Week</option>
</select>
</div>
<br /> <br />
<div class="input-group input-large" data-date="13/07/2013" data-date-format="dd/mm/yyyy">
<span class="input-group-addon">From</span>
<input type="text" id="txtDateFrom" class="form-control dpd1" name="from">
<span class="input-group-addon">To</span>
<input type="text" id="txtDateTo" class="form-control dpd2" name="to">
</div>
You should create two date objects for the cases where a week overlaps 2 months.
Because when you set the date to -5, from july 1st, 2017, it correctly calculates the date to sunday june 25th.
But now, the month has changed!
When you set the date to the last day of the week, which is 1, the month stays to june in the date object.
So having two different date objects to manipulate the dates separately is the fix.
$(document).on("change","#selectDates",function() {
var dropValue = document.getElementById('selectDates').value;
//All
if (dropValue == "1") {
$('#txtDateFrom').val('');
$('#txtDateTo').val('');
}
//Today
else if (dropValue == "2") {
var back_GTM = new Date();
$('#txtDateFrom').val(Back_date(back_GTM));
$('#txtDateTo').val(Back_date(back_GTM));
}
//This Week
else if (dropValue == "3") {
//var curr = new Date; // get current date
var curr = new Date('07/01/2017'); // get current date
var curr2 = new Date('07/01/2017'); // get current date - Second date object.
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first));
var lastday = new Date(curr2.setDate(last));
$('#txtDateFrom').val(Back_date(firstday));
$('#txtDateTo').val(Back_date(lastday));
}
});
function Back_date(back_GTM) {
var b_dd = back_GTM.getDate();
var b_mm = back_GTM.getMonth() + 1;
var b_yyyy = back_GTM.getFullYear();
if (b_dd < 10) {
b_dd = '0' + b_dd
}
if (b_mm < 10) {
b_mm = '0' + b_mm
}
return back_date = b_dd + '/' + b_mm + '/' + b_yyyy;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-style">
<select id="selectDates">
<option value="1" selected>All</option>
<option value="2">Today</option>
<option value="3">This Week</option>
</select>
</div>
<br /> <br />
<div class="input-group input-large" data-date="13/07/2013" data-date-format="dd/mm/yyyy">
<span class="input-group-addon">From</span>
<input type="text" id="txtDateFrom" class="form-control dpd1" name="from">
<span class="input-group-addon">To</span>
<input type="text" id="txtDateTo" class="form-control dpd2" name="to">
</div>
For creating new date you should pass year, month index and date of month as prameters.
Example as follows:
var curr = new Date(2017,6,1);
Following needs to be fixed in your code:
// Needs to fix this
var curr = new Date('07/01/2017');
To make the issue short. I have 3 dropdowns for picking a date. The date picker display the range of the days within the month if it's only 29 or 31 days. It's working fine now except that when I changed in different month the value in my days is repeating.
For example I choose February. The days that is display is 28 days.
Then I changed to March. The days displays as 31 days. The problem is they are only combining so the value in my day dropdown become many. How can I fixed this, any help?
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
function onMonthChange(){
var year = document.getElementById("yeardialog").value;
var month = document.getElementById("monthdialog").value;
var endOfTheMonth = daysInMonth(month, year);
console.log(endOfTheMonth);
var select = document.getElementById('datedialog');
for (var i = 0; i < endOfTheMonth; i++) {
select.options[select.options.length] = new Option(i + 1, i);
}
}
<select id="yeardialog" name="yeardialog">
<option value="">--</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
</select>
<select id="monthdialog" onchange="onMonthChange()">
<option value="">--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="datedialog">
<option></option>
</select>
var select = document.getElementById('datedialog');
select.innerHTML = ""; // clear the select.
for (var i = 0; i < endOfTheMonth; i++) {
select.options[select.options.length] = new Option(i + 1, i);
}
The solution is plain and simple. Delete the contents of the select before populating them.
Solution inside the snippet:
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
function onMonthChange(){
var year = document.getElementById("yeardialog").value;
var month = document.getElementById("monthdialog").value;
var endOfTheMonth = daysInMonth(month, year);
console.log(endOfTheMonth);
var select = document.getElementById('datedialog');
var selectedvalue = select.querySelector('option:checked');
if (selectedvalue)
{
var store = selectedvalue.getAttribute("value");
}
select.innerHTML = "";
for (var i = 0; i < endOfTheMonth; i++) {
select.options[select.options.length] = new Option(i + 1, i);
}
var retrieved = select.querySelector("option[value='"+store+"']");
if (retrieved)
{
retrieved.setAttribute("selected", "true");
}
}
<select id="yeardialog" name="yeardialog">
<option value="">--</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
</select>
<select id="monthdialog" onchange="onMonthChange()">
<option value="">--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="datedialog">
<option></option>
</select>
Updated question. Store the original value before deleting:
We look for the selected value using:
select.querySelector('option:checked');
Then we look if the value can be found in the new list. If so select the value. If not revert to 1. This happens when you select 31 and the month loaded only has 30 days.
I wouldn't modify the innerHTML, I prefer removing the nodes
var select = document.getElementById('datedialog');
while(select.hasChildNodes())select.removeChild(select.firstChild);// clear the select.
for (var i = 0; i < endOfTheMonth; i++) {
select.options.add(new Option(i + 1, i));
}
Try this:
function onMonthChange(){
var year = document.getElementById("yeardialog").value;
var month = document.getElementById("monthdialog").value;
var endOfTheMonth = daysInMonth(month, year);
console.log(endOfTheMonth);
var select = document.getElementById('datedialog');
select.innerHTML = '';
select.options[0] = new Option("Pick a date", 0);
for (var i = 1; i < endOfTheMonth; i++) {
select.options[select.options.length] = new Option(i + 1, i);
}
}
so i have this code that checks for dates and updates lists accordingly, now what i am trying to achieve is that when the for both the month and the year are set to null "mm" "yyyy" is set the day select list with one element "dd" with a value of null. but i have been having an error cannot set property 'value' of undefined. The first element in both the year and month s is set to a value of null.
this is the javascript function a guy here helped me come up with:
function monthDays (type) {
if(document.getElementById('monthof' + type).value == null || document.getElementById('yearof' + type).value == null)
{
var mod = document.getElementById('dayof' + type);
mod.length = 1;
mod[0].value = null;
mod[0].text = "DD";
}
else{
var month = parseInt(document.getElementById('monthof' + type).value, 10),
days = new Date(document.getElementById('yearof' + type).value, month + 1, 0).getDate(),
i;
var mod = document.getElementById('dayof' + type);
mod.length = days + 1;
mod[0].value = null;//this is where i am getting the error
mod[0].text = "DD";
for(i = 1; i < days+1; i++) {
mod[i].value = i;
mod[i].text = i;
}
}
}
html
Birth:
MM
<select id="dayofbirth" class="date" name="dayhofbirth">
<option value=null>DD</option>
</select>
<select id="monthofbirth" class="year" name="monthofbirth" onchange="monthDays('birth')">
<option value=null>MM</option>
</select>
<select id="yearofbirth" class="year" name="monthofbirth" onchange="monthDays('birth')">
<option value=null>YYYY</option>
</select>
</div>
the type is there to tell the function which it should edit, since in my html I have 2 date of births.
The object returned by getElementById( ) returns a reference to an element, not an array of options when you're selecting a select element. You can access the options through a property on the object but you don't need to do that to set the selected option. To set the selected option, just set the value like you are but remove the [0] part. You also need to set null as a string ('null') because it is a string value in the HTML.
Here's what I came up with for you:
HTML
<select id="dayofbirth" class="date" name="dayhofbirth">
<option value=null>DD</option>
<option value=01>01</option>
</select>
<select id="monthofbirth" class="year" name="monthofbirth" onchange="monthDays('birth')">
<option value=null>MM</option>
<option value=12>12</option>
</select>
<select id="yearofbirth" class="year" name="monthofbirth" onchange="monthDays('birth')">
<option value=null>YYYY</option>
<option value=1900>1900</option>
</select>
Javascript
function monthDays(type) {
if(document.getElementById('monthof' + type).value == null || document.getElementById('yearof' + type).value == null)
{
var mod = document.getElementById('dayof' + type);
mod.length = 1;
mod.value = 'null';
}
else{
var month = parseInt(document.getElementById('monthof' + type).value, 10),
days = new Date(document.getElementById('yearof' + type).value, month + 1, 0).getDate(),
i;
var mod = document.getElementById('dayof' + type);
mod.value = 'null';
for(i = 1; i < days+1; i++) {
mod.add(i);
}
}
}
See it in action here: http://jsfiddle.net/CT54h/
It probably doesn't do everything you want it to, but within the scope of the question it does.
I found out what I had to do, I set the values at the beginning of each to 'null' not null, and than when I checked for their value I also checked for 'null'. I think there might be some concept that I do not fully understand when it comes to but my method seemed to have solved my problem.