loop to check combination of dropdown & checkbox in pure javascript - javascript

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">

Related

Cascading dropdown list in HTML

Ok I edited the question with below update.
I tried with below script but it seems not working. Please someone can show me what is wrong with below code.
<script>
var myselect = document.getElementById("start2");
document.getElementById("end1").onchange = createOption()
function createOption() {
var selectEnd = document.getElementById("end1");
var value = selectEnd.options[select.selectedIndex].value;
var objOption = document.createElement("option");
objOption.text = value + 1;
objOption.value = value +1;
//myselect.add(objOption);
myselect.appendChild(objOption);
}
</script>
What I want to do is there are 2 select list form with id End1 and Start2. I want when select list End1 onchange, value from End1 will be passed to Start2 with added 1. But, it has nothing happened.
I have solved this problem. I want to share it. But, can I post it here as answer? Or need I to add in my first entry above?
<html>
<body id="myBody">
<table>
<%
for i = 1 to 5
%>
<tr>
<td>
<select id = "start<%=i%>" onChange="startChange(this.id)">
<option value=""></option>
</select>
</td>
<td>
<select id = "end<%=i%>" onChange="endChange(this.id)">
<option value=""></option>
</select>
</td>
</tr>
<%
next
%>
</table>
<script>
const serialEnd =+document.getElementById("start1").innerText + 100;
document.getElementById("myBody").onload = function() {optionLoad("end1")};
function optionLoad(id){
var lastno = +id.substring(3,4);
var selectElement = document.getElementById("end" + lastno + "");
var serialStart = +document.getElementById("start" + lastno + "").value;
for (var serial = serialStart + 1; serial <= serialEnd; serial++) {
selectElement.add(new Option(serial));
}
}
function endChange(id) {
var lastno = +id.substring(3,4);
var selectStart = document.getElementById("start" + ( lastno + 1 ) + "");
var selectEnd = document.getElementById(id);
var options = selectEnd.options[selectEnd.selectedIndex];
var objOption = document.createElement("option");
if (lastno != 5){
removeOptions(document.getElementById("start" + ( lastno + 1 ) + ""));
objOption.text = +options.value + 1;
objOption.value = +options.value + 1;
selectStart.add(objOption);
}
}
function startChange(id){
var lastno = +id.substring(5,6);
removeOptions(document.getElementById("end" + lastno + ""));
optionLoad("end" + lastno + "");
}
function removeOptions(selectElement) {
var i, L = selectElement.options.length - 1;
for(i = L; i >= 1; i--) {
selectElement.remove(i);
}
}
</script>
</body>
</html>

Adding values of dynamically created inputs [javascript]

I am creating my first bigger .js project from scratch and I'm completely stuck on one part. I am really new to web-dev and .js is my first programming language that I am learning. I want to create a dynamic calculator that allows for additional inputs to be added on button click. All that functionality is working however I do not know how to save and add values of all created inputs and then display their results added together.
My code only works for the first added input row, however even though each next input item has updated dynamic ID I do not know how to extract their values and use it in my function.I am assuming that arrays should play a big role in this, but it is just beyond my scope of understanding for now. I apologize if the code is a mess I am really into programming but this is only my first month. I would really appreciate all the help you can give.
function addItems() {
idIndex = idIndex + 1;
let newItem1 = document.createElement("div");
newItem1.innerHTML =
`<select id="select_euro${idIndex}" class="input_itemA input_item_new">
<option value="E6" class="option1">Euro 6</option>
<option value="E5" class="option2">Euro 5</option>
<option value="E4" class="option3">Euro 4</option>
<option value="E3" class="option4">Euro 3</option>
<option value="E2" class="option5">Euro 2</option>
<option value="E1" class="option6">Euro 1</option>
</select> ` +
`<input type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null" name="number_of_trucks" placeholder="L. Ciężarówek" id="input_item_truck${idIndex}" class="input_itemA input_item_new">
` +
`<select id="input_item_dmc${idIndex}" class="input_itemA input_item_new">
<option value="A" class="optionA">7,5t do 12t</option>
<option value="B" class="optionB">12 do 18t</option>
<option value="C" class="optionC">> 18t z 3 osi</option>
<option value="D" class="optionD">> 18t z 4 lub więcej osi</option>
</select>` +
`<input type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null" name="number_of_km" placeholder="Przejechane km" id="input_item_km${idIndex}" class="input_itemA input_item_new">
` +
`<button type="button" id="remove_input${idIndex}" class="btn_new_negative" onclick = remover()>-</button>`;
newItem1.setAttribute("id", "input_item" + idIndex);
newItem1.setAttribute("class", "input_item_new");
inputs.appendChild(newItem1);
let truckNoNew = document.querySelector(`#input_item_truck` + `${idIndex}`);
let euroClassNew = document.querySelector(`#select_euro` + `${idIndex}`);
let dmcNew = document.querySelector(`#input_item_dmc` + `${idIndex}`);
let truckKmNew = document.querySelector(`#input_item_km` + `${idIndex}`);
let span = document.querySelector("#result");
function calcTruckNew() {
if ((euroClassNew.value === "E6") & (dmcNew.value === "A")) {
let moneyAmount = truckKmNew.value * 0.014 * 11;
let resultNew = parseInt(moneyAmount * parseInt(truckNoNew.value));
span.textContent = resultNew;
} else if ((euroClassNew.value === "E6") & (dmcNew.value === "B")) {
let moneyAmount = truckKmNew.value * 0.002 * 11;
let resultNew = parseInt(moneyAmount * parseInt(truckNoNew.value));
span.textContent = resultNew;
} else if ((euroClassNew.value === "E6") & (dmcNew.value === "C")) {
let moneyAmount = truckKmNew.value * 0.004 * 11;
let resultNew = parseInt(moneyAmount * parseInt(truckNoNew.value));
span.textContent = resultNew;
} else if ((euroClassNew.value === "E6") & (dmcNew.value === "D")) {
let moneyAmount = truckKmNew.value * 0.005 * 11;
let resultNew = parseInt(moneyAmount * parseInt(truckNoNew.value));
span.textContent = resultNew;
}
}
btnCalc.addEventListener("click", calcTruckNew);
}
bntAdd.addEventListener("click", addItems);
//removes added inputs
function remover() {
btnRem = document.getElementById("remove_input" + idIndex);
newItem = document.getElementById("input_item" + idIndex);
newItem.parentNode.removeChild(newItem);
idIndex--;
}

Show field based on selection (JS)

I'm trying to show fields based on what is selected in menu select option.
I tried some JS with the help of other posts found here on Stackoverflow, but failed.
I'm a fan, i dont know js well, i hope to find help with this question. Thanks to everyone for any answers, I leave the info below.
I would like to show the result of this:
var dayli_intake_mass = ((+ target) / 100 * (+ tdee) + (+ tdee));
only when mass1, mass2 or mass3 is selected.
Otherwise
I would like to show the result of this:
var dayli_intake_def = ((+ tdee) - (+ target) / 100 * (+ tdee));
only when def1, def2 or def3 is selected.
So, the mass1, mass2 and mass3 selection should show dayli_intake_mass
While the selection def1, def2 and def3 should show dayli_intake_def
Point 1 is an addition, point 2 is a subtraction. I don't want both to be visible, but only one of the two fields based on the selection.
I apologize for the bad English :(
<div class="fieldcontainer">
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="4" id="tdee" name"tdee" placeholder="Inserisci il tuo TDEE" form="fbday" required autocomplete="off"/>
<label>Spesa calorica</label>
</div>
<div class="container_level">
<select class="target" id="target_select" form="fbday" name="target">
<option value="0">Stile di vita / Attività fisica</option>
<option id="mass1" name="radsa" value="5">mass1</option>
<option id="mass2" name="radsa" value="10">mass2</option>
<option id="mass3" name="radsa" value="15">mass3</option>
<option id="def1" name="radsa" value="10">def1</option>
<option id="def2" name="radsa" value="15">def2</option>
<option id="def3" name="radsa" value="20">def3</option>
</select>
</div>
<!---Fabbisogno Giornaliero--->
<div id="fbbday0" class="results" hidden>
<input type="text" form="fbday" class="result-field" id="dayli_intake_mass" name="dayli_intake"
placeholder="Fabbisogno giornaliero / 0.000 Kcal" min="1" readonly/>
<label class="mts-label"></label>
</div>
<div id="fbbday1" class="results" hidden>
<input type="text" form="fbday" class="result-field" id="dayli_intake_def" name="dayli_intake"
placeholder="Fabbisogno giornaliero / 0.000 Kcal" min="1" readonly/>
<label class="mts-label"></label>
</div>
<form action="" id="fbday">
</form>
<button name="calculate" onclick="calculate()">Calculate</button>
<button id="reset" onclick="resetFields()">Reset</button>
calculate = function()
{
var tdee = document.getElementById('tdee').value;
var target = document.querySelector('#target_select option:checked').value;
var dayli_intake_mass = ((+target)/100*(+tdee)+(+tdee));
var kcal = "Devi assumere "+dayli_intake_mass.toLocaleString('it-IT',{maximumFractionDigits: 0}) + " Kcal"; document.getElementById('dayli_intake_mass').value = kcal;
var dayli_intake_def = ((+tdee)-(+target)/100*(+tdee));
var kcal = "Devi assumere "+dayli_intake_def.toLocaleString('it-IT',{maximumFractionDigits: 0}) + " Kcal"; document.getElementById('dayli_intake_def').value = kcal;
//This is Target Radio Selection//
var mass1 = document.getElementById('mass1').value;
var mass2 = document.getElementById('mass2').value;
var mass3 = document.getElementById('mass3').value;
var def1 = document.getElementById('def1').value;
var def2 = document.getElementById('def2').value;
var def3 = document.getElementById('def3').value;
//This is HideShow Result//
var conditional = document.querySelector('#target_select option:checked').value;
document.getElementById('dayli_intake_mass').hidden = conditional !== '5';
document.getElementById('dayli_intake_mass').hidden = conditional !== '10';
document.getElementById('dayli_intake_mass').hidden = conditional !== '15';
document.getElementById('dayli_intake_def').hidden = conditional !== '10';
document.getElementById('dayli_intake_def').hidden = conditional !== '15';
document.getElementById('dayli_intake_def').hidden = conditional !== '20';
}
https://jsfiddle.net/snake93/w1nLbhxv/81/
Edited
you can use change event to handle that
when you select one of the list it's will call change event then check or execute your code
because of there's some values like each other for example mass2 value = 10 and also def1 value = 10 .
because of that you can't only compare the values but also you need to compare the element id so i added the id's in the comparison operation
Here's the code
var target_select = document.getElementById("target_select");
target_select.addEventListener("change", function () {
var tdee = document.getElementById('tdee').value;
var target = document.querySelector('#target_select option:checked');
var fbbday1 = document.getElementById('fbbday1'),
fbbday0 = document.getElementById('fbbday0')
var dayli_intake_mass = ((+target.value)/100*(+tdee)+(+tdee));
var dayli_intake_def = ((+tdee)-(+target.value)/100*(+tdee));
//This is Target Radio Selection//
var mass1 = document.getElementById('mass1').value;
var mass2 = document.getElementById('mass2').value;
var mass3 = document.getElementById('mass3').value;
var def1 = document.getElementById('def1').value;
var def2 = document.getElementById('def2').value;
var def3 = document.getElementById('def3').value;
var massArr = [mass1, mass2, mass3],
deffArr = [def1, def2, def3]
if(massArr.indexOf(this.value) != -1 && target.id === 'mass1' || target.id === 'mass2' || target.id === 'mass3') {
fbbday0.removeAttribute('hidden')
document.getElementById('dayli_intake_mass').value = dayli_intake_mass;
} else {
fbbday0.setAttribute('hidden', true)
}
if(deffArr.indexOf(this.value) != -1 && target.id === 'def1' || target.id === 'def2' || target.id === 'def3') {
fbbday1.removeAttribute('hidden')
document.getElementById('dayli_intake_def').value = dayli_intake_def;
} else {
fbbday1.setAttribute('hidden', true)
}
});
First, I edited the values of the select options to be as below:
<select class="target" id="target_select" form="fbday" name="target" (onChange)="showHideIntake($event)">
<option value="0">Stile di vita / Attività fisica</option>
<option id="mass1" name="radsa" value="5">mass1</option>
<option id="mass2" name="radsa" value="10">mass2</option>
<option id="mass3" name="radsa" value="15">mass3</option>
<option id="def1" name="radsa" value="-10">def1</option>
<option id="def2" name="radsa" value="-15">def2</option>
<option id="def3" name="radsa" value="-20">def3</option>
</select>
Second, I added an event called (onChange) to the select element as shown in the first line in the previous point.
Third, I added an eventListener to the select element to handle the (onChange) event, as below:
const target_select = document.querySelector('#target_select');
const dayli_intake_mass = document.querySelector('#dayli_intake_mass');
const dayli_intake_def = document.querySelector('#dayli_intake_def');
target_select.addEventListener('change', (event) => {
console.log(+event.target.value); // just for checking selected option
// the + (plus sign) is to convert from string to number
dayli_intake_mass.hidden = dayli_intake_def.hidden = true;
event.target.value > 0 ? dayli_intake_mass.hidden = false :
dayli_intake_def.hidden = false;
});
With this, dayli_intake_mass and dayli_intake_def are shown or hidden upon the select option. Plus, you can use the value of the select option directly upon select one option of them.

Javascript passing variable and elementId to an function

var ingaveA = {
stuks: ""
};
var ingaveB = {
prijs: ""
};
var uitgave = {
totaal: ""
};
update(ingaveA, "testa", ingaveB, "testb", uitgave, "testc");
function update(refA, argsA, refB, argsB, refC, argsC) {
refA.stuks = document.getElementById(argsA).value;
refB.prijs = document.getElementById(argsB).value;
refC.totaal = refA.stuks * refB.prijs;
document.getElementById(argsC).value = refC.totaal;
}
ingaveA = ingaveA.stuks;
ingaveB = ingaveB.prijs;
uitgave = uitgave.totaal;
alert("Stuks=" + ingaveA + " Prijs=" + ingaveB + " Totaal=" + uitgave);
<input id="testa" value="10">
<input id="testb" value="6">
<input id="testc" value="">
Is there an better way to do this? always 3 variable names and 3 elements.
Maybe using an array ?
thanks in advance
Instead of using document.getElementById() for every input, you can use document.querySelectorAll() and [id^=test] to select all 3 and put them in a NodeList (think of it as an array).
[id^=test] means every id that starts with test
You can also make one general object, and update it as needed like below.
var ingave = {
ingaveA: {
stuks: ""
},
ingaveB: {
prijs: ""
},
uitgave: {
totaal: ""
}
};
var inputs = document.querySelectorAll("[id^=test]");
update(ingave, inputs);
function update(ref, inputs) {
ref.ingaveA.stuks = inputs[0].value;
ref.ingaveB.prijs = inputs[1].value;
ref.uitgave.totaal = ref.ingaveA.stuks * ref.ingaveB.prijs;
inputs[2].value = ref.uitgave.totaal;
}
var ingaveA = ingave.ingaveA.stuks;
var ingaveB = ingave.ingaveB.prijs;
var uitgave = ingave.uitgave.totaal;
alert("Stuks=" + ingaveA + " Prijs=" + ingaveB + " Totaal=" + uitgave);
<input id="testa" value="10">
<input id="testb" value="6">
<input id="testc" value="">
I'm not really sure what the question is here, but you don't need to create 3 separate objects.
let ingaveA = ""
let ingaveB = ""
let uitgave = ""
then just pass these 3 to your function:
function update(refA, refB, refC) {
refA = document.getElementById("testa").value;
refB = document.getElementById("testb").value;
refC = refA * refB;
document.getElementById("testc").value = refC.totaal;
}
Again, it's hard to optimize it as we don't know your specifics of the code.

getting current year in a dropdown of years

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>
);
};

Categories

Resources