Reputation:
How to Trigger an function before drop down of select and abort dropdown if returned false?
maybe something like this:
document.querySelector('select').addEventListener('click',(e)=>{
if(check()==false)
e.target.abortdropdown();
})
Upvotes: 0
Views: 112
Reputation: 17566
You can put a container around the selectbox and bind it to the click event. then you check your check() function and can act on what happens to the select box. .
let check = () => {return false;};
const w = document.querySelector('#wrapper');
const s = w.querySelector('select');
w.addEventListener('click',(e) => {
const os = s.querySelectorAll('option');
if(check() == false){
s.setAttribute('onclick',"abortdropdown()");
console.log('check() is false');
abortdropdown(os);
} else {
console.log('check() is true');
setdropdown(os);
}
});
function abortdropdown(os) {
os.forEach((el) => {
el.classList.add('hide');
})
}
function setdropdown(os) {
os.forEach((el) => {
el.classList.remove('hide');
})
}
.hide {
display:none;
}
<div id="wrapper">
<select >
<option class="hide">1</option>
<option class="hide">2</option>
<option class="hide">3</option>
</select>
</div>
Here is a much better example. The wrapper / parent container (can also be your body) is triggered via mouseover in this example (load or similar would also fit). This checks your check() function. And would then set the selct box disabled or remove disabled. This should actually do what you want.
const parent = document.getElementById('parent');
const s = parent.querySelector('select');
let check = () => {return true;};
parent.addEventListener('mouseover', (e) => {
if(check() == false){
s.setAttribute('disabled',"disabled");
console.log('check() is false');
} else {
console.log('check() is true');
s.removeAttribute('disabled')
}
});
select[disabled] {pointer-events:none}
<div id="parent">
<select disabled>
<option class="hide">1</option>
<option class="hide">2</option>
<option class="hide">3</option>
</select>
</div>
Upvotes: 1
Reputation: 1
I think you are looking for this, https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault.
Then the if inner case should be.
If (check==false) {
e.target.preventDefault();
}
And that stops further default handling of the event.
Upvotes: 0