Search code examples
javascriptselectpreventdefault

Javascript : preventDefault() not working on a select tag?


I want to come back to the previous option when a user select a option which doesn't fulfill a condition. For exemple, this code :

    <select onchange="test_condition(this, event);">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>

    <script type="text/javascript">

    function test_condition(this_select, event)
    {
         /*If the value of selected option is not equal to 3, 
         come back to the previous option with event.preventDefault(); 
         but this isn't working :*/
         if(this_select.value != 3)
         {event.preventDefault();}
    }

    </script>

So if the select tag has the "2" option displayed (for exemple), and the user selects the "4" option, then the select must display the previous option, that is say the "2" option. But event.preventDefault is not working.

Have you a idea ?

Thank in advance, cordially.


Solution

  • I don't think you can use event.preventDefault() to prevent the select from updating onChange; however, you can work around this pretty easily. You can play around with this jsFiddle for my solution; I saved off the previous value and, if the new value doesn't match my criteria (in this case, if the new value isn't 3), I reassign it to the old value:

    $(function () {
      var previous_value = $('#test_select').val();
      test_condition = function test_condition(this_select, event) {
            console.log(this_select.value);
            /*If the value of selected option is not equal to 3, 
             come back to the previous option with event.preventDefault(); 
             but this isn't working :*/
            if (this_select.value != 3) {
                $('#test_select').val(previous_value);
            } else {
                previous_value = this_select.value;
            }
        }
    });
    

    I also ran into a problem where test_condition was not defined, and fixed that by assigning it to a variable as you can see above.