Я использую цепочки обещаний JavaScript для получения и загрузки проектов и периодов оплаты. Выбор периода оплаты заполняется опциями после выбора проекта в списке проектов.
После того, как пользователь нажимает «Отправить», я сохраняю записи времени в базе данных и обновляю цвета выделения выбранных опций. , в зависимости от статуса расписания (зеленый — одобрено, красный — отклонено, серый — отправлено). Мне нужно обновить списки вариантов выбора проекта и периода оплаты, чтобы параметры были выделены нужным цветом.
Для этого мне нужно вызвать getProjects() и getPayPeriods() еще раз и программно измените значения projectSelect и payPeriodSelect. Я могу изменить значение payPeriodSelect с помощью функции jQuery .val(). Однако для значения projectSelect установлено значение null, когда я использовал тот же метод. Почему это работает для одного выбора, а для другого нет?
Элементы выбора определяются следующим образом:
Код: Выделить всё
Код: Выделить всё
getProjects()
.then(data => {
return loadProjects(data);
})
.then(data => {
$('#projectSelect').change(); // select the default project to display (1st option in list)
})
.catch(error => {
// display error in modal
});
function loadProjects(projectData) {
return new Promise((resolve, reject) => {
let select = document.getElementById("projectSelect");
select.length = 0;
projectData.reduce((previousPromise, project) => { // map each project object in the array to a new promise
return previousPromise
.then(x => getPayPeriods(project.id))
.then(payPeriods => {
let option = document.createElement("option")
if (payPeriods.length) {
// if all timesheets for the project have been approved, change highlight color of option to green
if (payPeriods.every(payPeriod => payPeriod.approvalStatus)) {
option.setAttribute('class', 'approvedColor')
}
// If all timesheets are rejected, change color to red
else if (payPeriods.every(payPeriod => payPeriod.rejectionStatus)) {
option.setAttribute('class', 'rejectedColor')
}
// if all timesheets are submitted, change color to gray
else if (payPeriods.every(payPeriod => payPeriod.submissionStatus)) {
option.setAttribute('class', 'submittedColor')
}
}
option.text = project.code + ' - ' + project.name
option.value = project.id
select.appendChild(option)
select.value = select.options[0].value // set 1st option's project ID as default value
return resolve(true)
})
.catch(error => {
return reject(error)
})
}, Promise.resolve()) // Promise.resolve() is the initial promise function that starts the chain
return resolve(true);
})
}
Код: Выделить всё
$('#projectSelect').on('change', function (e) {
$('tr').find("input.timeBox").val("") // clear timesheet inputs
let projectId = this.value
getPayPeriods(projectId)
.then(data => {
return loadPayPeriods(data)
})
.then(x => {
$('#payPeriodSelect').trigger('change')
})
.catch(error => {
})
})
function loadPayPeriods(data) {
return new Promise((resolve, reject)=>{
var select = document.getElementById("payPeriodSelect")
select.length = 0
if (!data.length) {
$('#payPeriodSelect').attr('disabled', true)
return reject(false)
}
// enable dropdown if there are pay periods to load into it
$('#payPeriodSelect').attr('disabled', false)
for (let payPeriod of data) {
let option = document.createElement("option")
option.text = payPeriod.start_d + ' - ' + payPeriod.end_d
option.value = payPeriod.start_d + '|' + payPeriod.end_d
// change pay period option highlight colors based on timesheet status
if (payPeriod.approval_d) {
option.setAttribute('class', 'approved')
} else if (payPeriod.rejection_d) {
option.setAttribute('class', 'rejected')
} else if (payPeriod.submission_d) {
option.setAttribute('class', 'submitted')
}
select.appendChild(option)
}
select.value = select.options[0].value
return resolve(true)
})
}
Код: Выделить всё
$('#payPeriodSelect').on('change', function (e) {
// get and populate timesheet data for the selected pay period
getTimeData(this.value)
.then(data=> {
return loadTimeData(data)
})
.then(data => {
if (data) {
let payPeriodSelect = document.getElementById('payPeriodSelect')
if (data.approvalStatus) {
payPeriodSelect.options[payPeriodSelect.selectedIndex].setAttribute('class', 'approvedColor')
} else if (data.rejectionStatus) {
payPeriodSelect.options[payPeriodSelect.selectedIndex].setAttribute('class', 'rejectedColor')
} else if (data.submissionStatus) {
payPeriodSelect.options[payPeriodSelect.selectedIndex].setAttribute('class', 'submittedColor')
}
}
})
.then(x => {
return calculateTotalTime()
})
.catch(error => {
})
})
Код: Выделить всё
$('#submitTol').on('click', function (e) {
return saveDataToDatabase()
.then(data => {
return getProjects()
})
.then(data => {
return loadProjects(data)
})
.then(x => {
return new Promise((resolve, reject) => {
$('#projectSelect').val(project.id).change()
return resolve(true)
})
})
.then(x => {
return new Promise((resolve, reject) => {
$('#payPeriodSelect').val( payPeriod.start_d + '-' + payPeriod.end_d).change()
return resolve(true)
})
}
}
Подробнее здесь: https://stackoverflow.com/questions/781 ... hange-valu