0

I have a drop down- If user tries to submit the page, but doesn't choose an option from the dropdown, then I want an ALERT message box to appear, then for the page to stay where it is instead of navigating to another page.

Currently, the drop down appears, but the page still redirects to another page. How do I prevent this?

I tried "return false" but it didn't work...

function validateDropDown() {

var e = document.getElementById("colors"); var strUser = e.options[e.selectedIndex].value;

var strColor1 = e.options[e.selectedIndex].text;

var strColor = e.options[e.selectedIndex].text;
            if(strColor==0)
            {
                alert("Please select a color");
                return false;//This is what I tried to prevent page redirection, but it doesn't work.
            }

}

Mohan Aravind
  • 53
  • 1
  • 7

2 Answers2

0

Use prevent default:

function validateDropDown(event) {

var e = document.getElementById("services1"); var strUser = e.options[e.selectedIndex].value;

var strUser1 = e.options[e.selectedIndex].text;

var strUser1 = e.options[e.selectedIndex].text;
            if(strUser==0)
            {
                alert("Please select a service");
                event.preventDefault();
            }
}
Abid Hasan
  • 648
  • 4
  • 10
0

Instead of returning false inside your function you can use event.preventDefault() as explained by W3, it does exactly what you are looking for

function validateDropDown(event) { // add the parameter event 

var e = document.getElementById("services1"); 
var strUser = e.options[e.selectedIndex].value;

var strUser1 = e.options[e.selectedIndex].text;

var strUser1 = e.options[e.selectedIndex].text;
            if(strUser==0) {
                alert("Please select a service");
                event.preventDefault(); // add prevent Default
            }
}

Resources :

Mozzila

W3 schools

Also an explanation of stack overflow exists :

Stack overflow

Muhammad Salman
  • 433
  • 6
  • 18