ボタンをクリックすると、新しい入力が追加されるフォームがあります。送信時にはすべてが正常に機能しますが、ブラウザーに戻ると、追加されたすべてのフィールドが失われます..
このブラウザのボタンを押したときにそれらを維持する方法はありますか?
ありがとう!
追加された要素は、ブラウザーによってキャッシュされない DOM にのみ存在します。
この問題を解決するには Cookie を使用することをお勧めします。https://github.com/carhartl/jquery-cookieを確認してください。
そのようなクッキーに何かを追加するには
$.cookie("row", "a new row or whatever");
// or preferably a json
var myJsonRow = {
row: 1,
value: "Test"
}
$.cookie("row", JSON.stringify(myJsonRow));
この非常に単純な Cookie を読み取るには、次のようにします。
$.cookie("row");
明らかに、これよりも高度なものが必要になりますが、これは json オブジェクトで処理できます。
次のような、快適に感じるjsonパターンを作成することから始めます
// Basic row-pattern
var cookieRows = {
rows: [
{
value: "row 1",
type: "radio"
},
{
value: "row 2",
type: "text"
},
{
value: "row 3",
type: "password"
},
]
}
そして実装
$(document).ready(function(){
// Test if the cookie is set
if(!$.cookie("rows")) {
var cookieRows = {
rows: []
}
// Register the pattern
$.cookie("rows", JSON.stringify(cookieRows));
}
// Adding rows
// Register your event handler
$("#control").click(function(){
// Get the control element
var controlElement = $(this);
// Fetch the needed information and create a row
var cookieRow = {
value: controlElement.val(),
type: controlElement.attr('type')
}
// Get the cookie
var cookieRows = JSON.parse($.cookie("rows"));
// Add the value to the cookie
cookieRows.rows.push(cookieRow);
// And save the cookie
$.cookie("rows", JSON.stringify(cookieRows));
});
});
ああ、あなたはその考えを理解します!