user6758349
user6758349

Reputation:

How to reload page and update selection when a new value is selected in JQuery

I have a select box. On page load, "5" is selected, when I select "1" from the list, I want to reload the page and have 1 be selected on default. How do I accomplish this in JQuery.

<span> 
    There are  
    <select class="num_apples form-control">
        <option value="1">1</option>
        <option value="5" selected="selected">5
        </option><option value="50">50</option>
    </select>
    apples on the table
</span>

I tried doing this in JQuery

$(".num_apples").change (function() {
      $(this).val = $(".num_apples").selected;
      location.reload();
});

Upvotes: 3

Views: 9581

Answers (2)

Sylvain B
Sylvain B

Reputation: 550

You can set the selected value in local storage.

<span> 
    There are  
    <select id="mySelect" class="num_apples form-control">
        <option value="1">1</option>
        <option value="5" selected="selected">5</option>
        <option value="50">50</option>
    </select>
    apples on the table
</span>

The JavaScript code :

<script>
    $(document).ready(function(){
        var mySelectBoxVal = localStorage.getItem("mySelectBoxVal");
        if (mySelectBoxVal !== '') {
            $('#mySelect').val(mySelectBoxVal);
        }

        $("#mySelect").on('change',function() {
            selectBoxVal = $('#mySelect').val();
            if (typeof(Storage) !== "undefined") {
                localStorage.setItem("mySelectBoxVal", selectBoxVal);
            } else {
                alert('Sorry! No Web Storage support..');
            }
            location.reload();
        });
    });
</script>

Upvotes: 1

empiric
empiric

Reputation: 7878

Save the selected value and check on page load if a value is saved and set the value of the select accordingly:

var selected = localStorage.getItem('selected');
if (selected) {
  $(".num_apples").val(selected);
}


$(".num_apples").change(function() {
  localStorage.setItem('selected', $(this).val());
  location.reload();
});

Example

Upvotes: 4

Related Questions