javascript JQuery - 单击提交按钮获取表单值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27704828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:51:45  来源:igfitidea点击:

JQuery - Click Submit Button Get Form Value

javascriptjqueryformsdom

提问by user982853

I have the following function and all i am trying to do is get the value out of the form field.

我有以下功能,我要做的就是从表单字段中获取值。

$( ".searchbutton" ).click(function() {
    var tc = $(this).closest("form input[name='searchbox']").val();
    alert(tc);      
    return false;
}); 

The alert keeps telling me "Undefined". I have treid closest, parent, parents, find, etc. I don't know what im doing wrong. Im clicking the submit button and all i want in return is the value in the search box. Please help.

警报一直告诉我“未定义”。我已经 treid 最亲近的,父母,父母,找到等。我不知道我做错了什么。我点击提交按钮,我想要的只是搜索框中的值。请帮忙。

html

html

<form action="/index.php" method="get" class="qsearch" >
<input type="text" id="fsearch" name="searchbox" >
<input class="searchbutton" type="submit" value="Submit">
</form>

回答by Vladimir Chichi

Try this:

试试这个:

$( ".searchbutton" ).click(function() {
    var tc = $(this).closest("form").find("input[name='searchbox']").val();
    alert(tc);      
    return false;
}); 

UpdateYep, it work with your HTML - see here http://jsfiddle.net/qa6z3n1b/

更新是的,它适用于您的 HTML - 请参阅此处http://jsfiddle.net/qa6z3n1b/

As alternative - you must use

作为替代方案 - 您必须使用

$( ".searchbutton" ).click(function() {
    var tc = $(this).siblings("input[name='searchbox']").val();
    alert(tc);      
    return false;
}); 

in your case. http://jsfiddle.net/qa6z3n1b/1/

在你的情况下。http://jsfiddle.net/qa6z3n1b/1/

回答by Priyank

Try easiest way:

尝试最简单的方法:

<script>
$( ".searchbutton" ).click(function() {
var tc = $('#fsearch').val();
alert(tc);      
return false;
}); 
</script>

回答by jyrkim

How about just using $('input[name="searchbox"]')selector:

只使用$('input[name="searchbox"]')选择器怎么样:

$( ".searchbutton" ).click(function() {
    var tc = $('input[name="searchbox"]').val();
    alert(tc);      
    return false;
});