user2871282
user2871282

Reputation: 9

I create input field using jquery, how can keep this ' new input value ' exist after refresh page

I create input field using jquery, how I can keep this ' new input value ' exist after refresh page

the code is

function onMyButtonclick() 
        {   var a =$('#addItem').val()
            $('#resultList').append('<li>'+a +'</li>');
            $('#addItem').val("");

        }
<input type="button"  value="add" onClick="onMyButtonclick();">
<ol id="resultList">
    <li>just example</li>
</ol>
</form>

solution is so important ..

Upvotes: 1

Views: 642

Answers (2)

iPao
iPao

Reputation: 1163

use localstorage

var data = JSON.parse(localStorage.getItem('a')) || [];
//do something with data array
data.push($('#addItem').val());
localStorage.setItem('a', JSON.stringify(data));

Upvotes: 0

dade
dade

Reputation: 3570

You have to understand that on page refresh, the DOM is reconstructed again, so there is no straight way to have this "new input value" exist after page refresh, since it was added to the DOM programmatically on user interaction.

But not withstanding, you have other mechanism in the browser that can be used to persist information even on page refresh. You have cookies, and other set of Storage related feature which includes localStorage, sessionStorage, globalStorage. You can read about these features here DOM Storage Guide. for your situation, LocalStorage would be most appropriate.

So basically the solution you need would have you modify the onMyButtonClick function to store the information about the input item that has been added in any of the above browser persistence mechanism. And when the page loads again on refresh, you write a new function that takes information that you stored to generate the input elements again.

I would also advice you read the article: THE PAST, PRESENT & FUTURE OF LOCAL STORAGE FOR WEB APPLICATIONS

Upvotes: 2

Related Questions