MShack
MShack

Reputation: 652

save to localStorage

i'm curious if its possible to save the text input a user types in the field to localStorage , so in this html example , i'd want to save the innner html from the div#match_player_id , that is created when you click the button

<input type="text" id="contract_year" placeholder="Contract" autocomplete="off">

<input value="Submit" onclick="document.querySelector('#match_player_id').innerHTML = document.querySelector('#contract_year').value" type="button">

<div id="match_player_id"></div>

Upvotes: 0

Views: 143

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly, you should really be using unobtrusive event handlers to hook to events instead of the outdated on* event attributes. As you've tagged jQuery in the question this can be done incredibly simply.

From there you can just use localStorage.setItem() to save the value you require, like this:

$('button').click(function(e) {
  e.preventDefault();

  var contractYear = $('#contract_year').val();
  $('#match_player_id').html(contractYear);

  localStorage.setItem(contractYear);
});
<input type="text" id="contract_year" placeholder="Contract" autocomplete="off">
<button type="button">Submit</button>
<div id="match_player_id"></div>

Working example

Upvotes: 0

Eduardo Escobar
Eduardo Escobar

Reputation: 3389

I recommend you to use a javascript function instead:

<script type="text/javascript">
function updateMatchPlayerId() {
    var matchPlayerId = document.querySelector('#contract_year').value;
    document.querySelector('#match_player_id').innerHTML =  matchPlayerId;
    if (typeof Storage !== "undefined") {
        localStorage.setItem("matchPlayerId", matchPlayerId);
    }
}
</script>

HTML:

<input type="text" id="contract_year" placeholder="Contract" autocomplete="off">

<input value="Submit" onclick="updateMatchPlayerId()" type="button">

<div id="match_player_id"></div>

Upvotes: 3

Related Questions