问题
How to add/delete data from datalist via jquery with add and delete button? Will it also be possible to store datalist in localstorage?
*The reason behind this is that its going to be per-user-input-datalist. much like "type it once and store it"
Please help, Thanks in advance.
回答1:
Just in case someone else wants to accomplish the same method, Here's how I manage to pull this off: (if there's a better or efficient way please share it :)
var datarray = [];
function deldata() {
// retrieve stored data (JSON stringified) and convert
var storedData = localStorage.getItem("list_data_key");
if (storedData) {
datarray = JSON.parse(storedData);
}
var titleValue = document.getElementById('listxt').value;
// Find and remove item from an array
var i = datarray.indexOf(titleValue);
if (i > -1) {
datarray.splice(i, 1);
}
localStorage.setItem("list_data_key", JSON.stringify(datarray));
datapost();
show();
$('#listxt').val('');
}
function insert() {
var titleValue = document.getElementById('listxt').value;
datarray[datarray.length] = titleValue;
// store array to localstorage
localStorage.setItem("list_data_key", JSON.stringify(datarray));
show();
$('#listxt').val('');
}
function show() {
var content = "<b>All Elements of the Arrays :</b><br>";
for (var i = 0; i < datarray.length; i++) {
content += datarray[i] + "<br>";
}
document.getElementById('display').innerHTML = content;
datapost();
}
function datapost() {
var options = '';
for (var i = 0; i < datarray.length; i++)
options += '<option value="' + datarray[i] + '" />';
document.getElementById('bankit').innerHTML = options;
}
$(window).load(function() {
// retrieve stored data (JSON stringified) and convert
var storedData = localStorage.getItem("list_data_key");
if (storedData) {
datarray = JSON.parse(storedData);
}
show();
datapost();
});
JSFIDDLE
回答2:
Use can use jQuery click functions and localStorage.setItem() along with localStorage.removeItem(), here's a link with more information on webstorage if you're interested... https://www.w3schools.com/html/html5_webstorage.asp
HTML:
<button id="add">Add</button>
<button id="delete">Delete</button>
jQuery:
$('#add').click(function() {
localStorage.setItem("foo", "bar");
});
$('#delete').click(function() {
localStorage.removeItem("foo");
});
来源:https://stackoverflow.com/questions/46330828/onclick-add-delete-data-from-datalist-in-localstorage