mcclosa mcclosa - 3 months ago 11
Javascript Question

Get id's of each item in array and append to each item in option value

Apologies for any incorrect use of terminology, I am new to Javascript but hopefully I can explain the outcome I am expecting to help to answer my question.

In my code below, I have an array of

dates
in which the output is...

["25/08/2016", "24/08/2016", "23/08/2016", "22/08/2016", "21/08/2016", "20/08/2016", "19/08/2016", "18/08/2016", "17/08/2016"]


I then loop through these dates and append each date to a html select option, the output is as follows...

<select id="dayConstraintList" class="form-control input-lg">
<option value="25/08/2016">25/08/2016</option>
<option value="24/08/2016">24/08/2016</option>
<option value="23/08/2016">23/08/2016</option>
<option value="22/08/2016">22/08/2016</option>
<option value="21/08/2016">21/08/2016</option>
<option value="20/08/2016">20/08/2016</option>
<option value="19/08/2016">19/08/2016</option>
<option value="18/08/2016">18/08/2016</option>
<option value="17/08/2016">17/08/2016</option>
</select>


Below is my current code

var dates = [],
end = moment(endDate),
dif = moment(endDate, 'YYYY-MM-DD').diff(moment(startDate, 'YYYY-MM-DD'), 'days');

if(dif <= 0) {
return;
}

for(var i = 0; i < dif; i++) {
dates.push(end.subtract(1,'d').format('DD/MM/YYYY'));
}

var option = '';
for (var i = 0; i < dates.length; i++) {
option += '<option value="' + dates[i] + '">' + dates[i] + '</option>';
}
console.log(dates);
$('#dayConstraintList').empty();
$('#dayConstraintList').append(option);


This is the outcome I expect, how can I achieve this? Any help would be greatly appreciated?

<select id="dayConstraintList" class="form-control input-lg">
<option value="0">25/08/2016</option>
<option value="1">24/08/2016</option>
<option value="2">23/08/2016</option>
<option value="3">22/08/2016</option>
<option value="4">21/08/2016</option>
<option value="5">20/08/2016</option>
<option value="6">19/08/2016</option>
<option value="7">18/08/2016</option>
<option value="8">17/08/2016</option>
</select>

Answer

You have to change this part of code :

for (var i = 0; i < dates.length; i++) {
    option += '<option value="' + dates[i] + '">' + dates[i] + '</option>';
}

By :

for (var i = 0; i < dates.length; i++) {
    option += '<option value="' + i + '">' + dates[i] + '</option>';
}