简体   繁体   English

如何获得输入类型的文本值? 在jQuery中

[英]how to get input type text value? in jquery

This is just simple code but not working.. 这只是简单的代码,但不起作用。

why not working...?? 为什么不工作... ?? I'm confuse.. 我感到困惑。

<html>
    <head>
        <h3> Hello Web</h3>
        <br>
    </head>

    <body>
        <input type="text" name="textvalue" id="textvalue" />
        <input type="submit" name="submit" value="SAVE" />
    </body>

</html> 

<--! <-! jquery --> jQuery的->

function hello(){
    $var=$('#textvalue').val();


    alert($var);

}

Your html should contain a button 您的html应该包含一个按钮

<input type='button' id='btnSubmit' value='submit'>

it jquery should be like this 它的jQuery应该是这样的

$("#btnSubmit").on('click',function(e){
e.preventDefault();
hello();
}

change var value = $('#textvalue').val(); alert(value); 更改var value = $('#textvalue').val(); alert(value); var value = $('#textvalue').val(); alert(value);

The script must be connected at the end of the body. 脚本必须连接在正文的末尾。

<body>
<input type="text" name="textvalue" id="textvalue" />
<input type="submit" name="submit" value="SAVE" />
<script src="js.js"
<body>

And where do you call the function hello()? 在哪里调用函数hello()?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Place the above line of code in head and than try. 将上面的代码行放在头部,然后尝试。 it will work.. 它会工作..

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function hello(){
    $var=$('#textvalue').val();


    alert($var);

}
</script>
</head>
<body>

 <input type="text" name="textvalue" id="textvalue" />
        <input type="submit" name="submit" onclick="hello()" value="SAVE" />

</body>
</html>

The reason that your code was not working is you did not call you function hello at any event. 您的代码无法正常工作的原因是您在任何情况下均未调用函数hello

You should not write as below 你不应该写如下

<head>
   <h3> Hello Web</h3>
   <br>
</head>

It should be like 应该像

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>

<form id="test-form" action="someurl" method="POST">
  <input type="text" name="textvalue" id="textvalue" />
  <input type="submit" name="submit" value="SAVE" />
</form>

</body>
</html>

Below is the solution for your problem. 以下是您的问题的解决方案。

 jQuery(document).ready(function($) { $('#test-form').submit(function(event) { // Prevent form submission event.preventDefault(); alert("Form submission prevented"); var textValue = $('#textvalue').val(); // Alert the value alert("textValue = " + textValue); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="test-form" action="someurl" method="POST"> <input type="text" name="textvalue" id="textvalue" /> <input type="submit" name="submit" value="SAVE" /> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM