javascript jquery从表单中获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11855781/
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
jquery getting data from form
提问by gilbertbw
I have a form that I'm trying to get data from a form using jquery and validate it. What is the best way to take data from a form to a variable using jquery?
我有一个表单,我正在尝试使用 jquery 从表单中获取数据并对其进行验证。使用 jquery 将数据从表单获取到变量的最佳方法是什么?
采纳答案by devang
Here is the snippet that you can use -
这是您可以使用的代码段 -
$('#myForm').submit(function() {
// get all the inputs into an array.
var $inputs = $('#myForm :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
});
Got it from stackoverflow-link
回答by Alberto Bellini
Well here we go
好吧,我们走了
This is the jQueryscript:
这是jQuery脚本:
function getData () {
$(document).ready(function() {
var myTextFieldValue = $('#myTextField').value;
alert('The value is: '+myTextFieldValue);
});
}
This is the HTML
这是HTML
<form action='#' method='whatever'>
<input type='text' id='myTextField' />
<input type='submit' onClick='getData()' />
</form>
NOTE:In order to make your script working you must import the jQuery Libraries
注意:为了使您的脚本工作,您必须导入 jQuery 库
Like this:
像这样:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
I Did not try the script so there could be some errors. Hope i was helpful to you Bye.
我没有尝试脚本,所以可能会出现一些错误。希望我对你有帮助再见。
(For any help pm me)
(有任何帮助请私信我)
回答by Nickydonna
there no way to get all the data from a form in one line of code. You have to retrieve it value by value.
if you have a <input id='some-id' >
just use var someId = $('#some-id').val();
. Now someId hold the value of the input
没有办法在一行代码中从表单中获取所有数据。您必须按值检索它。如果你有一个<input id='some-id' >
刚刚使用的var someId = $('#some-id').val();
. 现在 someId 保存输入的值
The val() function only return the value of the first matched element (if you don't know what i mean take a look at jquery selector (http://api.jquery.com/category/selectors/)
take a look at http://api.jquery.com/val/to see the val function, it has some weird thing with the <textarea>
tag
val() 函数只返回第一个匹配元素的值(如果你不知道我的意思,看看 jquery 选择器(http://api.jquery.com/category/selectors/)看看http://api.jquery.com/val/查看 val 函数,它的<textarea>
标签有一些奇怪的东西
And remember to always validate server side, even if you already did it client side, js securrity is very easy to bypass
并记住始终验证服务器端,即使您已经在客户端验证过,js 安全性也很容易绕过