简体   繁体   中英

Storing data in javascript for server side processing

The problem is simple. I have something like chessboard in HTML. The fields have coordinates, stored in ID attribute (ROW|COLUMN) Clicking on a specific field makes it marked/unmarked. What is more, selected field's row and column are stored in a <input type="hidden"/> in the form of ROW|COLUMN,ROW|COLUMN,...

For every click I have to process the value of input hidden to check whether the field is already stored, add new field, remove existing and so on. It's a little awkward. Are there any better ways? Or maybe it is the best way?:)

You don't have to store the fields state in an input field. Better use the a global JavaScript array or manipulate the DOM and serialize it's state before sending it to the server.

Here is some sample code in a JSFiddle: http://jsfiddle.net/U2D9Q/

The important part is where the className of the columns

$td.bind("click", function(e) {
    $(this).toggleClass("selected");
});

and how it's serialized when you click the button

var serialize_table = function() {
    var output = new Array();

    $("table tbody").children().each(function(y) {
        var row = new Array();

        $(this).children().each(function(x) {
            row[x] = $(this).get(0).className;
        });

        output[y] = row;
    });

    return output;
}

I used jQuery to keep the code clean. Feel free to use any JS Framework you like or write native JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM