2016-12-30 74 views
1

你好,我今天剛剛開始,所以我很新。HTML/JavaScript - 輸入值不更新(Element.value = Null)

我要得到一個字符串,用戶可以在網站上進入我的JavaScript文件。我發現我應該使用document.getElementById("myID").value來獲取html網站上的輸入字段的值。這是我的問題:我不能使用圍繞我的輸入和按鈕的括號,因爲提交將強制重新加載該網站,我的功能將不會有任何影響。

所以我得在運行過程中串入我的JavaScript文件。

這是我目前所面對的:

<div id="searchDiv"> 
    <input type="text" id="searchInput" placeholder="Search for Gifs..." value="" /> 
    <input type="button" id="searchButton" value="Search"></button> 
</div> 

我的JavaScript文件:

var searchButton = document.getElementById("searchButton"); 
var searchInput = document.getElementById("searchInput").value; 

searchButton.addEventListener("click", 
    function() { 
    function(parameter) 
    } 
)... 

所以document.getElementById("searchInput").value;放棄,即使輸入字段已被編輯回零。

我希望你能幫助我。

+0

您是否獲得*空*或空字符串是什麼? – RobG

+0

空字符串,但問題是,我訪問前值有人甚至已經進入任何 – redii

回答

3

這是因爲你被存儲在單擊按鈕之前也searchInput值,因此該值將是無論你輸入輸入

嘗試訪問該按鈕的Click事件的任何空

檢查這個片段

var searchButton =document.getElementById("searchButton"); 
 
var searchInput=document.getElementById("searchInput"); 
 
window.onload=function(){ 
 
searchButton.addEventListener("click", 
 
    function() { 
 
    alert(searchInput.value); 
 
    } 
 
) 
 
}
<div id="searchDiv"> 
 
    <input type="text" id="searchInput" placeholder="Search for Gifs..." value="" /> 
 
    <input type="button" id="searchButton" value="Search"> 
 

 
</div>

希望它有助於

+0

如果它的任何幫助考慮接受答案 – Geeky

0

您應該使用

<button></button> 

而不是

<input></button> 

我所做的就是

<div id="searchDiv"> 
     <input type="text" id="searchInput" placeholder="Search for Gifs..."> 
     <button id="searchButton">Search</button> 
    </div> 

    <script type="text/javascript"> 
     document.getElementById("searchButton").onclick = function(){ 
      alert(document.getElementById("searchInput").value); 
     } 
    </script> 
+0

呀IM現在玩這個兜了幾個小時哈哈 – redii