2014-03-01 36 views
0

我試圖獲取userinput的值,但我的代碼無法正常工作。如何從javascript輸入文本中獲取值

HTML

<body> 
<button id="test">test</button> 
<form> 
    <input type="text" id="test1"> 
</form> 
</body> 

的javascript:

var text = null; 

$(document).ready(function(){ 
    text = $("#test1").value; 
    $("#test").on("click", testing); 

}); 

function testing(){ 
    console.log("something"); 
    if(text == "top"){ 
     console.log("top"); 
    } 
} 
+0

的可能重複[jQuery的:試圖獲得的輸入值(http://stackoverflow.com/questions/3788910/jquery-trying-to-get-the-input-value) – Vasu

回答

0

您可以使用val()

text = $("#test1").val(); 

你也需要移動上面一行的testing函數內部,將其檢查值您點擊按鈕時的輸入。所以,最終的代碼看起來象:

var text = null; 

$(document).ready(function(){ 
    $("#test").on("click", testing); 
}); 

function testing(){ 
    console.log("something"); 
    text = $("#test1").val(); 
    if(text == "top"){ 
     console.log("top"); 
    } 
} 

Fiddle Demo

0

jQuery中它val(),不value,這對本地DOM工作節點只

text = $("#test1").val(); 

而且真的沒有必要全局在這裏,你應該確保在cli時更新值該死的按鈕,現在它只能存儲在DOM準備

$(document).ready(function(){ 
    $("#test").on("click", testing); 
}); 

function testing(){ 
    var text = $("#test1").val(); 

    if(text == "top"){ 
     console.log("top"); 
    } 
} 
0

只是這將工作

$("#test").click(function(){ 
    var value = $("#test1").val(); 
    alert(value); check value by alert 
}); 
0

您可以使用.val()方法 jQuery中

DEMO

text = $("#test1").val(); 
相關問題