2017-10-16 73 views
1

我在學校有一個項目。這個項目是關於創建一個網頁形式,用戶可以選擇一個活動,然後繼續填寫他們的個人信息。然後必須在管理頁面上打印這些信息,根據他們的選擇,您應該能夠看到有關該特定人員在特定活動下的所有信息。保存用戶回答提交到本地存儲

我正在努力的是如何讓他們選擇的活動與<select><option>標籤出現在local.storage中。因爲我不知道他們會選擇什麼。

我創建了一個函數onsubmitted named sportVal()。我不應該能夠通過在我的JS這樣的事情?:

function sportVal() { 
 
    var sportVal = document.getElementById("sportList").value; 
 
    localStorage.setItem("sportList"); 
 
}
<form onsubmit="sportVal()" name="frmDataEntry" action="Uppgifter.html" method="POST"> 
 
    <select id="sportList"> 
 
     <option id="Tennis" value="Tennis">Tennis</option> 
 
     <option id="Fotboll" value="Fotboll">Fotboll</option> 
 
    </select> 
 
    </br> 
 
    <input id="Knapp" type="submit" value="Gå vidare >>" /> 
 
</form>

+0

是的,那是事後事後的錯誤。它應該是setItem。但是,是否有可能通過setItem獲取用戶選擇的值? –

+0

那麼,既然你已經設置了它,你應該可以在以後使用getItem' –

+1

來閱讀[documentation](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem)。你需要一個關鍵字_和_一個值爲'setItem':'.setItem(「sportList」,sportVal)'。 – Xufox

回答

1

使用localStorage.getItem(「sportList」)你試圖返回的值來獲取信息一個名爲'sportList'的項目已經在您的存儲中。 要保存在localStorage的東西,你應該使用:

localStorage.setItem('nameOfItem', itemValue); 

在你的情況下,你可以得到並保存這樣

var e = document.getElementById("sportList").value; 
localStorage.setItem('selectedItem', e); 

要素只要記住,如果你需要保存一個對象,你將有可能將它串起來。

JSON.stringfy(yourObject) 

據Mozilla docs

「存儲接口的setItem()方法,當通過一個鍵名 和價值,將是關鍵添加到存儲,或更新密鑰的 如果它已經存在,那麼值。「


存儲接口的的getItem()方法,當通過一個鍵名, 將返回鍵的值。

0

這應該工作。你的代碼的第一個問題是你的函數聲明實際上並沒有將你存儲的值傳遞給localstorage。

function sportVal() { 
    var sportVal = document.getElementById("sportList").value; 
    localStorage.setItem("sportList",sportVal); 
    //get value of from local storage 
    var result=localStorage.getItem("sportList") 
    alert(result); 
}