vendredi 31 mars 2017

How can I check if there is a value for a key in local storage?

The user should only be able to store information if there is not a preexisting value stored to the key. How can i check if there is already a value, and alert the user that there is already a value? I know i have to use an if statement. If there is a value alert the user. Else set item...(save the object). But how do i check for the value?

function addEvent() {
var announcement = {
    title: document.getElementById('title').value,
    group: document.getElementById('group').value,
    author: document.getElementById('author').value,
    type: document.getElementById('type').value,
    date: document.getElementById('date').value,
    time: document.getElementById('time').value,
    gender: document.getElementById('gender').value,
    grade: document.getElementById('grade').value,
    message: document.getElementById('message').value
    };
var objS = JSON.stringify(announcement);

localStorage.setItem('announcement', objS);

alert('Announcement successfully stored!');

}

function showA() {
var getObj = localStorage.getItem('announcement');
var objP = JSON.parse(getObj);

document.getElementById('showAnnouncement').innerHTML = "Announcement"+"<br/>Title:"+objP.title+"<br/>Group:"+objP.group+"<br />Author:"+objP.author+"<br />Type:"+objP.type+"<br/>Date:"+objP.date+"<br />Time:"+objP.time+"<br/>Gender:"+objP.gender+"<br/>Grades:"+objP.grade+"<br />Message:"+objP.message;

}

Aucun commentaire:

Enregistrer un commentaire