Home > Mobile >  JS Onchange display value before processing
JS Onchange display value before processing

Time:08-17

I have a form with a select input element. After the user selects an option, I check that option chosen. If it is bigger than I expected, I bring up an alert box asking the user if they're sure they selected the right option. This is just a warning, so I don't reset the value or prevent the user from selecting these options.

Currently, this causes the alert to display first, and then the option on the webpage is changed AFTER they hit OK.

How can I get the value in a select element to display the selection before I process it during the onchange event?

mySelectElement.onchange = function() {
    if(mySelectElement.value >= 1000) {
        alert("Are you sure you can eat that many apples?");
    }
    // else nothing, less than 1000
};

CodePudding user response:

A couple solutions, one don't use an alert. You can use a modal library, or just output to the dom.

If you must use an alert,wrap it in a setTimeout so its delayed.

let select = document.querySelector("select");

select.addEventListener("change",function(){
  if(select.value > 1){
    setTimeout(function(){alert("Alert");},100);
  } 
});
<select ><option value="0">A</option><option value="3">3</option></select>

  • Related