DEgITx
DEgITx

Reputation: 980

Working form without action

I'm trying to do html form without action. It must:

1) Remember input data as normal form do.

2) Doesn't reload page

I tried:

<form action="javascript:void(0);" id="simple-form">

But on

$('#simple-form').submit();

form didn't remember input data. Normal form

<form action="#" id="simple-form">

reloads page but also remembers input data.

Does exist another way to remember data without forms with javascript?


Update #1:

event.preventDefault(); // onsubmit event prevert

Doesn't work same because it's preventing not only reload of page but also saving of data (autocomplete).

Upvotes: 1

Views: 3563

Answers (1)

Winchestro
Winchestro

Reputation: 2188

With javascript

var form = document.getElementById("simple-form")
form.onsubmit = function (event) { event.preventDefault() }

if(localStorage){
    var textfield = document.getElementById("yourTextfield");
    var data = localStorage.getItem("yourTextfield");
    if(data){
       textfield.value = JSON.parse(data);
    }
    textfield.onkeydown = function(){
         localStorage.setItem("yourTextfield",JSON.stringify(textfield.value));
   }
}

ok alternative solution with history object

var data = history.state.textfieldName;
if(data){
    textfield.value = data;
}
textfield.onkeydown = function(){
    history.state.textfieldName = textfield.value;
}

Upvotes: 1

Related Questions