Ben Everard
Ben Everard

Reputation: 13804

Click (mousedown) event of a select element

I have an empty select element, I want to execute some code when that element is clicked on, but I do not want the dropdown list to appear, here is what I have found:

  1. When I disabled the select element I cannot catch the mousedown event.
  2. When I enable the select element I can capture the mousedown event but the dropdown list appears.

For arguements sake what I want is to be able to click the select element, JavaScript to throw an alert box but I want to prevent the dropdown list from displaying.

Thanks!

Upvotes: 1

Views: 11235

Answers (3)

TomaszO
TomaszO

Reputation: 38

<script>
function makeDisable(){
    var x=document.getElementById("mySelect")
    x.disabled=true
}
function makeEnable(){
    var x=document.getElementById("mySelect")
    x.disabled=false
}
function f() {
makeDisable();
alert("something");
t=setTimeout("makeEnable();",1);
}
</script>

<select id="mySelect" onMouseDown="f();">
  <option value="opt1">Option 1</option>
  <option value="opt2">Option 2</option>
</select>

Upvotes: -1

gp.
gp.

Reputation: 8225

capture onmousedown event of select element and cancel the event by setting event.returnValue to false.

<script type="text/javascript">
    function onSelectMouseDown() {
        event.returnValue = false;
        alert("mouse down caught and cancelled");
    }
</script>

<select id="select" onmousedown="onSelectMouseDown();"></select>

Upvotes: 3

TomaszO
TomaszO

Reputation: 38

Why not to disable a select element and wrap the select element in a div (or something else) of the same height and width as the select element and use mousedown event with this div?

Upvotes: 0

Related Questions