如果存在下拉列表的默认值,我不希望启用提交按钮。
这是我的代码中与我的问题相关的部分:
function checkSelect(select) {
if (select.value == '-- select an option --') submit.disabled = true;
else submit.disabled = false;
}
(function() {
if (checkSelect(starting)) {
starting.addEventListener('change', function(e) {
startingEventVal = returnAirPort(e.srcElement.value);
console.log('startingEventVal', startingEventVal);
});
}
if (checkSelect(destination)) {
starting.addEventListener('change', function(e) {
startingEventVal = returnAirPort(e.srcElement.value);
console.log('startingEventVal', startingEventVal);
});
}
})();
这就是我的所有代码:
(function() {
var starting = document.getElementById('starting'),
destination = document.getElementById('destination'),
submit = document.getElementById('submit'),
airportNames = Object.keys(IntentMedia.Airports.airport_distances()),
startingEventVal,
destinationEventVal;
function appendToUL(ul, element) {
var optionEL = document.createElement('option');
optionEL.text = element;
optionEL.value = element;
return ul.appendChild(optionEL);
}
function returnAirPort(airport) {
return airport;
}
function checkSelect(select) {
if (select.value == '-- select an option --') submit.disabled = true;
else submit.disabled = false;
}
airportNames.forEach(function(element) {
appendToUL(starting, element);
appendToUL(destination, element);
});
(function() {
if (checkSelect(starting)) {
starting.addEventListener('change', function(e) {
startingEventVal = returnAirPort(e.srcElement.value);
console.log('startingEventVal', startingEventVal);
});
}
if (checkSelect(destination)) {
starting.addEventListener('change', function(e) {
startingEventVal = returnAirPort(e.srcElement.value);
console.log('startingEventVal', startingEventVal);
});
}
})();
submit.addEventListener('click', function(e) {
e.preventDefault();
var distance = IntentMedia.Distances.distance_between_airports(startingEventVal, destinationEventVal);
console.log('distance', distance);
document.getElementById('feedback').innerHTML = distance;
});
})();
任何帮助将不胜感激!
答案 0 :(得分:1)
修复此功能:
//This is wrong because select.value refers to the value property of the select
//and you are comparing that to the selected option's text
function checkSelect(select) {
if (select.value == '-- select an option --') submit.disabled = true;
else submit.disabled = false;
}
将其更改为:
//Compare the selected option's text to see if it equals the default option text
function checkSelect(select) {
if (select.options[select.selectedIndex].text == '-- select an option --') submit.disabled = true;
else submit.disabled = false;
}
答案 1 :(得分:0)
在click事件中,尝试在if语句中检查输入的值并执行:
return;
如果它们是默认值
,则退出该函数