Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options on a select changed with jquery but strange results with Chrome

I have this site - http://kingsberryfuels.com/ - which, if you visit on a chrome browser and select gas oil as a fuel type then with jquery I'm changing the options in the select below. If you have home heating oil you can choose lots of options, not so with gas oil.

Anyway, when I choose gas oil and choose one of the limited options then click to go to the next page, if I then hit the back button, when I get back to the previous page I see the fuel type is still gas oil, but the options in the select for quantity isn't the correct limited options.

This only happens in Chrome, with Firefox everything works like I'd expect. Can anyone help me out?

The js/php I'm using is :

var homeOptions = {
        <?php foreach($oilHome as $liter) {
                echo '"'.$liter['litres'].'": "'.$liter['litres'].'",';
        }?>
};
var businessOptions = {
        <?php foreach($oilOil as $liter) {
                echo '"'.$liter['litres'].'": "'.$liter['litres'].'",';
        }?>
};
$("#fueltype").change(function() {
        var $el = $("#quantity");
        var fueltype = $("#fueltype").val();
        if(fueltype == 'Home Heating Oil') {
                var newOptions = homeOptions;
        } else {
                var newOptions = businessOptions;
        }
        $el.empty(); // remove old options
        $.each(newOptions, function(key, value) {
          $el.append($("<option></option>")
                 .attr("value", value).text(key));
        });

});
like image 776
Zaphod Beeblebrox Avatar asked Nov 07 '15 13:11

Zaphod Beeblebrox


1 Answers

The problem you're experiencing isn't necessarily the code, and it's actually not a "problem" with Chrome. It's actually Firefox doing more than perhaps it 'should'. What's happening is when you go "back", firefox is re-selecting your options based on what it remembers (for ease of use for the browser user). When firefox does this, it looks for "change" events, and fires them. Chrome does not. Just add a trigger to the function to force the update to occur when the page first loads.

$("#fueltype").change(function() {
    var $el = $("#quantity");
    var fueltype = $("#fueltype").val();
    if(fueltype == 'Home Heating Oil') {
            var newOptions = homeOptions;
    } else {
            var newOptions = businessOptions;
    }
    $el.empty(); // remove old options
    $.each(newOptions, function(key, value) {
      $el.append($("<option></option>")
             .attr("value", value).text(key));
    });

}).trigger('change');
like image 140
Refuting logic Avatar answered Oct 20 '22 18:10

Refuting logic