MaryAnn MaryAnn - 3 months ago 11
Javascript Question

How to update values in local storage dynamically,on button click?

This is my code used for adding values to local storage.

var textval=0;
function addValue(){
console.log(typeof(localStorage.getItem(textval)));
textval= localStorage.length+1;
var fieldValue = $('#textfield').val();
localStorage.setItem(textval, fieldValue);
textval = 0;
}


now, If I want to edit the value in local storage,what to do for that?

My HTML code used for updation lies below:-
<input class="form-control" id="ex2" type="text" placeholder="Enter the key"><br>
<input class="form-control" id="ex21" type="text" placeholder="Enter the updated value"><br>
<button type="button" class="btn btn-primary" onClick="editValue();">Enter</button>


When I click Enter button after specifing the key and updated value in text box,those changes should reflect in my localstorage.What I have to do for that?
Please help me.Thanks in advnace..

Answer

Try using a select and the following editValue function

<div class="parent">
<select class="form-control" id="ex2" name="key"></select><br>
<input class="form-control" id="ex21" type="text" placeholder="Enter the updated value"><br>
<button type="button" class="btn btn-primary"    onClick="editValue();">Enter</button>
</div>

js:

 for (var i = 0; i < localStorage.length; i++) {
    $('#ex2').append('<option value="'+localStorage.key(i)+'">'+localStorage.key(i)+'</option>');
  };

function editValue() {
   var key = $(this).closest('.parent').find('option:selected').val();
  localStorage.setItem(key,$(this).closest('.parent').find('input[type="text"]').val());
}
Comments