Search code examples
javascriptjqueryajaxpreventdefault

Prevent loading page when changing select value


I got this select tag in my form, which contains the name of a room

<select class = 'form-control' id = 'room_select' name = 'room'>".$rooms."</select>

I got 4 rooms so this select contains 4 options

$(document).ready(function(){
$("select").msDropDown();
$("#room_select").change(function(e){
    e.preventDefault();
    $("#room_select_form").submit();  
});
$("#room_select option[value='<?php echo $room; ?>']").attr('selected', 'selected');
});

Then I got this doc ready function first one .msDropDown(); is to be able to get images in the options. Then I got the change function which I googled around and put in a preventdDefault to not refresh page, (still refresh) I thought that I could use an ajax funciton to do this but I dont really know how to write it down or even if it works.

So currently the problem is that my function changes the room value as seen last in the code, but it refreshes the select tag and I see room nr 1 again,


Solution

  • Your page is getting refreshed, because you are submitting the form in onchange listener. You need to put e.preventDefault(); in your form submit listener to prevent default form submit and then you can call ajax in you submit listener.

    $(document).ready(function(){
    $("select").msDropDown();
    $("#room_select").change(function(e){
        $("#room_select_form").submit();  
    });
    $("#room_select option[value='<?php echo $room; ?>']").attr('selected', 'selected');
    $("#room_select_form").submit(function(e){
      e.preventDefault(); // to prevent page refresh
      // your Ajax call goes here....
    
    });
    });