Browser back button when selecting a list of values

I am trying to save a list of values ​​from dropdowns when a browser button is clicked after a form is submitted. I tried using bbq jQuery Ben Alman but couldn't get everything to work. Here 's what I tried. Please, help.

Thank you very much in advance.

Html

<form action="something.py" id="formName">
    <table id = "tabName">
        <tr>
            <th>Name</th><th>Number</th>
        </tr>
        <tr>
            <td>
                <select id="myname" name="myname">
                    <option value="a">a</option>
                    <option value="b">b</option>
                    <option value="c">c</option>
                </select>
            </td>
            <td>
                <select id="mynumber" name="mynumber">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
            </td>
        </tr>
    </table>
    <input type="submit" value="submit" />
</form>

      

JQuery

var selected_value = [];
$('#mynumber').change(function() {
    var name = $('#myname').val();
    var number = $('#mynumber').val();

    $("#tabName tr:last").before("<tr><td>" + name + "</td><td>" + number + "</td></tr>");
    selected_value.push(name);
});

$('#formName').submit(function() {
    $.bbq.pushState({
        values: selected_value
    });
    //return false;
});

$(window).bind("hashchange", function(e) {
    var values = $.bbq.getState("url");
    if (selected_value === values) {
        $(this).addClass("current");
    } else {
        $(this).removeClass("current");
    }
});

      

+3


source to share


2 answers


My solution (no cookies or localStorage) based on location.hash:

function addRow(name, number){
    $("#tabName tr:last").before("<tr><td>" + name + "</td><td>" + number + "</td></tr>");
}

$(function(){
    if(location.hash){
        var rows = location.hash.substr(1).split(';');
        for(var i = 0; i < rows.length; i++){
            var row = rows[i].split(',');
            if(row.length == 2){
                addRow(row[0], row[1]);
            }
        }
    }

    $('#mynumber').change(function() {
        var name = $('#myname').val();
        var number = $('#mynumber').val();
        location.hash = location.hash + (location.hash ? ';' : '') + name + ',' + number;
        addRow(name, number);
    });
});

      



I think it does what you asked for - if not, please give me some comments in the comments.

+4


source


$('#formName').submit(function() {
    $.bbq.pushState({
        values: selected_value
    });
    //return false;
});

      

it should be

$('#formName').submit(function() {
    $.bbq.pushState({
        values: selected_value
    });
    //return false;
});

      

and



var values = $.bbq.getState("url");

      

it should be

var values = $.bbq.getState("values");

      

0


source







All Articles