Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot preventDefault via Firefox on a <select>

Trying to preventDefault a keydown event in Firefox on a <select> but it does not work.

Any workaround?

For once something that even IE handles but Firefox does not!

See the code here:

http://jsfiddle.net/p8FNv/1/

<select id="select">
    <option value="1">Monday</option>
    <option value="2">Tuesday</option>
    <option value="3">Wednesday</option>
    <option value="4">Thursday</option>
    <option value="5">Friday</option>
    <option value="6">Saturday</option>
    <option value="7">Sunday</option>
</select>

$(document).ready(function() {

    $("#select").keydown(function (event) {
        event.preventDefault();
        event.stopPropagation();        
    });         
});
like image 487
Trant Avatar asked Feb 28 '13 17:02

Trant


People also ask

What can I use instead of event preventDefault?

The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault() . Nowadays, you should usually use native HTML form validation instead.

Why e preventDefault () is used?

The preventDefault() method is used to prevent the browser from executing the default action of the selected element. It can prevent the user from processing the request by clicking the link. Parameters: It does not accept any parameter.

What is the difference between stopPropagation and preventDefault?

stopPropagation prevents further propagation of the current event in the capturing and bubbling phases. preventDefault prevents the default action the browser makes on that event.

What is the opposite function of preventDefault?

As you probably might have already worked out based on the simple explanation above: the opposite of event. preventDefault() is nothing. You just don't prevent the event, by default the browser will allow the event if you are not preventing it.


2 Answers

This is not much elegant but works:

$("select").keydown(function(e){
    e.preventDefault();
    var elem = this;
    elem.disabled=true;
    setTimeout(function() { elem.disabled = false; }, 0);
});

A greeting.

like image 119
SegmentationFault Avatar answered Sep 29 '22 08:09

SegmentationFault


This seems to be working for me on Firefox 19. I am assuming your intention is to prevent the select value from changing via keyboard input when a user types in a value.

$(document).ready(function() {
    var valueToKeep;
    $("#select").keypress(function (event) {
        $(this).val(valueToKeep);
    });
    $("#select").keydown(function (event) {
        event.preventDefault();
        event.stopPropagation();
        valueToKeep = $(this).val();

    });         
});

JSFiddle

like image 30
danronmoon Avatar answered Sep 29 '22 06:09

danronmoon