[英]how to get value out of input text in javascript
I'm trying to get the value of the userinput, but my code isn't working properly. 我正在尝试获取userinput的值,但是我的代码无法正常工作。
html html
<body>
<button id="test">test</button>
<form>
<input type="text" id="test1">
</form>
</body>
javascript: 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");
}
}
in jQuery it's val()
, not value
, which works on native DOM nodes only 在jQuery中,它是
val()
,而不是value
,仅适用于本机DOM节点
text = $("#test1").val();
And there's really no need for globals here, and you should make sure the value is updated when clicking the button, right now it's only stored on DOM ready 而且这里确实不需要全局变量,并且您应该确保在单击按钮时更新了该值,现在它仅存储在DOM上。
$(document).ready(function(){
$("#test").on("click", testing);
});
function testing(){
var text = $("#test1").val();
if(text == "top"){
console.log("top");
}
}
You can use val() : 您可以使用val() :
text = $("#test1").val();
Also you need to move above line inside your testing
function to make it check the value of your input when the button clicked. 另外,您还需要在
testing
功能内的行上方移动,以使其在单击按钮时检查您输入的值。 So final code look like: 因此最终代码如下所示:
var text = null;
$(document).ready(function(){
$("#test").on("click", testing);
});
function testing(){
console.log("something");
text = $("#test1").val();
if(text == "top"){
console.log("top");
}
}
Just this will work 只是这会工作
$("#test").click(function(){
var value = $("#test1").val();
alert(value); check value by alert
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.