Home > Web Front-end > JS Tutorial > How to get all the values ​​of the form in js (code attached)

How to get all the values ​​of the form in js (code attached)

不言
Release: 2018-08-28 16:48:15
Original
7995 people have browsed it

The content of this article is about how to get all the values ​​of the form in js (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Usually obtaining all the input boxes of the form is to obtain the node value through the document dom object

<form>
<input id="a1" type="input" value="" name="a1"><br>
<input id="a2" type="input" value="" name="a2"><br>
<input id="a3" type="input" value="" name="a3"><br>
<input id="a4" type="input" value="" name="a4"><br>
<input id="submit" type="button" value="提交" name="submit">
</form>
Copy after login

Let’s compare it through two methods:

<script>
$(function() {
$(&#39;#submit&#39;).click(function() {
						
//方法1:
var a1 = document.getElementsById("a1").value;
//var a1 = document.getElementsByName("a1").value;
						
//要是提交json的格式的话还需要
var json ={"a1":a1}
						
//这样子转化一下,一个两个10个input还是可以接受的,但是实际开发中往往几十个 这样子就显得很笨重了,所以推荐方法二
						
//方法二:
var d = {};
var t = $(&#39;form&#39;).serializeArray(); // 默认是json 格式
						
//传统的for循环,将值打印出来
/*
console.info(t)
						
for (var i = 0;i<t.length;i++) {
console.info(t[i]);
d[t[i].name] =  t[i].value;
							
}
						
*/
						
//jQuery的循环
$.each(t, function() {
//console.info(t)
d[this.name] = this.value;
console.info(d)
}); 
						
console.info(JSON.stringify(t));   //从json对象解析出json字符串
var json_str = JSON.stringify(t);
						
console.info(JSON.stringify(d)); //从一个对象解析出字符串
});
});
</script>
Copy after login

Method one:

Use original js to obtain the value

Method 2:

Use jquery function library to obtain

Related recommendations:

How to js Get the selected value of the radio radio button

How to get the value and number of elements of the drop-down list in js

The above is the detailed content of How to get all the values ​​of the form in js (code attached). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template