I am building out a dynamic dropdown field that gets populated with all the “Saturdays” during a 3 month period. The dropdown is being populated correctly but I am getting duplicate ‘options’ added after the closing </select>
input. I don’t know what could be causing this. Below in the Javascript when I console.log(formatted);
the values only appear ONCE in the Chrome console.
WordPress, Contact Form 7
Dev: Laragon localhost
<select name="dates" class="wpcf7-form-control wpcf7-select wpcf7-validates-as-required span6 dates" aria-required="true" aria-invalid="false">
<option value="0">Saturday, June 18</option>
<option value="1">Saturday, June 25</option>
<option value="2">Saturday, July 2</option>
<option value="3">Saturday, July 9</option>
<option value="4">Saturday, July 16</option>
<option value="5">Saturday, July 23</option>
<option value="6">Saturday, July 30</option>
<option value="7">Saturday, August 6</option>
<option value="8">Saturday, August 13</option>
<option value="9">Saturday, August 20</option>
<option value="10">Saturday, August 27</option>
</select>
// HERE'S the issue - Duplicate options added to my page
<option value="0">Saturday, June 18</option>
<option value="1">Saturday, June 25</option>
<option value="2">Saturday, July 2</option>
<option value="3">Saturday, July 9</option>
<option value="4">Saturday, July 16</option>
<option value="5">Saturday, July 23</option>
<option value="6">Saturday, July 30</option>
<option value="7">Saturday, August 6</option>
<option value="8">Saturday, August 13</option>
<option value="9">Saturday, August 20</option>
<option value="10">Saturday, August 27</option>
Contact Form 7
[select* dates class:span6 class:dates "Sat, Jun 04"]
Javascript
jQuery(document).ready(function($) {
// Date object
var date = new Date();
var year = date.getFullYear();
var this_month = date.getMonth();
var this_day = date.getDate();
var num_months = 3;
// Select input
var select = $('.contact .dates');
select.find('option').remove();
// 3 months of Saturdays
let index = 0;
for (var i = 0; i < num_months; i++) {
var cur_month = this_month + i;
// Loop through each day of the month
for (var j = 0; j <= new Date(year, cur_month, 0).getDate(); j++) {
var date = new Date(year, cur_month, j);
// Find Saturdays and append option to select input
if (date.getDay() == 6){
let day = "Saturday, ";
let dayNum = date.getDate();
let month = date.toLocaleString('default', { month: 'long' });
// Don't include past Saturdays for the current month
if (dayNum<this_day && date.getMonth()==this_month){
continue;
}
let formatted = day + month + " "+ dayNum;
//let value = date.toString('dddd, MMMM ,yyyy');
select.append($('<option></option>').attr('value', index).text(formatted));
index += 1;
console.log(formatted); // This only outputs once NOT twice
}
};
}
});