I'm looking to essentially build an object dynamically where a property be the inputs name and the value of that property will be the inputs value.
我想要动态地构建一个对象,其中一个属性是输入名,这个属性的值是输入值。
Here's HTML
这是HTML
<form>
<fieldset>
<legend>form</legend>
<label>First<input type="text" value="null" name="first"/></label>
<label>Last<input type="text" value="null" name="last"/></label>
<label>Email<input type="text" value="null" name="email"/></label>
<input type="submit" value="submit"/>
</fieldset>
</form>
Here's the jQuery I'm using so far.
I have stored the values in and names in separate arrays. Is there a way to create some sort of associative array or to create an object where property names are taken from one array and values taken from another?
这是我目前使用的jQuery。我已经将值和名称存储在单独的数组中。是否有一种方法可以创建某种关联数组,或者创建一个对象,其中从一个数组中获取属性名,从另一个数组中获取属性名?
var values = new Array();
var names = new Array();
$("form").submit(function(event){
event.preventDefault();
values = [];
names = [];
$('form input').not('[type="submit"]').each(function(){
values.push($(this).val());
});
$('form input').not('[type="submit"]').each(function(){
names.push($(this).attr("name"));
});
});
I've also tried the .serializeArray() and it returns an array of Objects. But then I have no idea how to pull all of the key/value pairs out of that object and into a new one.
我还尝试了. serializearray(),它返回一个对象数组。但是我不知道如何将所有的键/值对从那个对象中取出并放入一个新的对象中。
The end goal is to not send this data over ajax but to send to a third party that aggregates data for analytics. Please help. I'm self taught and totally lost. Haha. Thanks
最终的目标不是通过ajax发送数据,而是将数据发送给聚合数据用于分析的第三方。请帮助。我是自学的,完全迷失了方向。哈哈。谢谢
PS
PS
I tried this
我试着这
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
var input = $("form").serializeArray();
$.each(input, function(i, field){
console.log(JSON.stringify(input[i]));
});
});
but it returns this
但它返回这
{"name":"first","value":"null"}
{"name":"last","value":"null"}
{"name":"email","value":"null"}
which seems to be equally as unhelpful. Haha.
这似乎同样没有帮助。哈哈。
I would love to be able to get an outcome as such
我希望能有这样的结果
{
"first" : "null",
"last" : "null",
"email" : "null"
}
3 个解决方案
#1
2
Easiest way I can think of is to use serializeArray
and then reduce that to an object or map. For example
我能想到的最简单的方法是使用serializeArray,然后将其简化为对象或映射。例如
$('form').on('submit', e => {
e.preventDefault();
let values = $(this).serializeArray().reduce((map, input) => {
let value;
if (map.hasOwnProperty(input.name)) {
value = Array.isArray(map[input.name]) ?
map[input.name] : [map[input.name]];
value.push(input.value);
} else {
value = input.value;
}
map[input.name] = value;
return map;
}, {});
})
This handles <select multiple>
and <input type="checkbox">
elements by setting the named value as an array.
它通过将命名值设置为数组来处理 <选择多个> 和 元素。
JSFiddle demo here ~ https://jsfiddle.net/wmjeh5Lv/1/
这里是JSFiddle demo ~ https://jsfiddle.net/wmjeh5Lv/1/
Legacy version
遗留版本
$('form').on('submit', function(e) {
e.preventDefault();
var values = $(this).serializeArray().reduce(function(map, input) {
var value;
if (map.hasOwnProperty(input.name)) {
value = Array.isArray(map[input.name]) ?
map[input.name] : [map[input.name]];
value.push(input.value);
} else {
value = input.value;
}
map[input.name] = value;
return map;
}, {});
})
#2
1
This should work, though realistically I don't understand the need for it. Check your browser's console. It gave me: {first: "null", last: "null", email: "null"}
这应该是可行的,尽管实际上我不明白这样做的必要性。检查你的浏览器的控制台。它给了我:{first: "null", last: "null", email: "null"}
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var arrObj = {};
$(this).find('input:not(:submit)').each(function(i, el) {
el = $(el);
arrObj[el.attr('name')] = el.val();
});
console.log(arrObj);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<legend>form</legend>
<label>First
<input type="text" value="null" name="first" />
</label>
<label>Last
<input type="text" value="null" name="last" />
</label>
<label>Email
<input type="text" value="null" name="email" />
</label>
<input type="submit" value="submit" />
</fieldset>
</form>
<div id="results">
</div>
Quick bit about Scope and Functions
Note: I am not a javascript expert, I have no formal education on it these are simply the things I've learned in using javascript.
注意:我不是javascript专家,我没有正式的教育,这些只是我在使用javascript中学到的东西。
- If you define a variable outside a function, you can use it inside*
- 如果你在函数外定义一个变量,你可以在*内使用它
Using the same code I gave you, you could do something like this:
使用我给你的代码,你可以这样做:
$(document).ready(function() {
var arrObj = {};
//Notice, arrObj is now defined OUTSIDE of our form.onsubmit function
$('form').on('submit', function(e) {
e.preventDefault();
$(this).find('input:not(:submit)').each(function(i, el) {
el = $(el);
arrObj[el.attr('name')] = el.val();
});
console.log(arrObj);
});
$('button').on('click', function() {
console.log(arrObj);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<legend>form</legend>
<label>First
<input type="text" value="null" name="first" />
</label>
<label>Last
<input type="text" value="null" name="last" />
</label>
<label>Email
<input type="text" value="null" name="email" />
</label>
<input type="submit" value="submit" />
</fieldset>
</form>
<button>Click me and Check Console<small>*Must click submit button first</small></button>
- This goes up as far as you want it to.
- 只要你想,它就会上升。
Got a variable you defined outside the $(document).ready(...)
and you want to use it? Go ahead. Javascript don't care.
在$(document).ready(…)之外定义了一个变量,您想要使用它吗?去做吧。Javascript不关心。
- When in doubt, create another function that you can return from somewhere else, like so (this involves using
$.fn.extend()
to add a new method to every jquery object) - 当有疑问时,创建可以从其他地方返回的另一个函数(这涉及到使用$.fn.extend()向每个jquery对象添加新方法)
$.fn.extend({
formObject: function() {
var arrObj = {};
$(this).find('input:not(:submit)').each(function(i, el) {
el = $(el);
arrObj[el.attr('name')] = el.val();
});
return arrObj;
}
});
$(document).ready(function() {
$('button').on('click', function() {
alert('check console');
console.log($('form').formObject());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<legend>form</legend>
<label>First
<input type="text" value="null" name="first" />
</label>
<label>Last
<input type="text" value="null" name="last" />
</label>
<label>Email
<input type="text" value="null" name="email" />
</label>
</fieldset>
</form>
<button>Click Me</button>
These are not the only ways, and if I am honest I don't even think they're the best ways, but they're the fastest ways using what we already have.
这些不是唯一的方法,如果我诚实的话,我甚至不认为它们是最好的方法,但它们是使用我们已有的方法最快的方法。
#3
0
I don't understand why the submit button if the only need it go generate an object?
我不明白为什么提交按钮只需要生成一个对象?
So here is my try only to generate the output without arrays ...
这里我只尝试生成没有数组的输出…
function generate() {
var obj = {};
$('form input').not('[type="submit"]')
.each((index, input) => obj[input.name] = input.value);
$('#result').text(JSON.stringify(obj));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form>
<fieldset>
<legend>form</legend>
<label>First<input type="text" value="null" name="first"/></label>
<label>Last<input type="text" value="null" name="last"/></label>
<label>Email<input type="text" value="null" name="email"/></label>
<button onclick="generate()">Generate</button>
</fieldset>
</form>
<br>
<div id="result"></div>
#1
2
Easiest way I can think of is to use serializeArray
and then reduce that to an object or map. For example
我能想到的最简单的方法是使用serializeArray,然后将其简化为对象或映射。例如
$('form').on('submit', e => {
e.preventDefault();
let values = $(this).serializeArray().reduce((map, input) => {
let value;
if (map.hasOwnProperty(input.name)) {
value = Array.isArray(map[input.name]) ?
map[input.name] : [map[input.name]];
value.push(input.value);
} else {
value = input.value;
}
map[input.name] = value;
return map;
}, {});
})
This handles <select multiple>
and <input type="checkbox">
elements by setting the named value as an array.
它通过将命名值设置为数组来处理 <选择多个> 和 元素。
JSFiddle demo here ~ https://jsfiddle.net/wmjeh5Lv/1/
这里是JSFiddle demo ~ https://jsfiddle.net/wmjeh5Lv/1/
Legacy version
遗留版本
$('form').on('submit', function(e) {
e.preventDefault();
var values = $(this).serializeArray().reduce(function(map, input) {
var value;
if (map.hasOwnProperty(input.name)) {
value = Array.isArray(map[input.name]) ?
map[input.name] : [map[input.name]];
value.push(input.value);
} else {
value = input.value;
}
map[input.name] = value;
return map;
}, {});
})
#2
1
This should work, though realistically I don't understand the need for it. Check your browser's console. It gave me: {first: "null", last: "null", email: "null"}
这应该是可行的,尽管实际上我不明白这样做的必要性。检查你的浏览器的控制台。它给了我:{first: "null", last: "null", email: "null"}
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var arrObj = {};
$(this).find('input:not(:submit)').each(function(i, el) {
el = $(el);
arrObj[el.attr('name')] = el.val();
});
console.log(arrObj);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<legend>form</legend>
<label>First
<input type="text" value="null" name="first" />
</label>
<label>Last
<input type="text" value="null" name="last" />
</label>
<label>Email
<input type="text" value="null" name="email" />
</label>
<input type="submit" value="submit" />
</fieldset>
</form>
<div id="results">
</div>
Quick bit about Scope and Functions
Note: I am not a javascript expert, I have no formal education on it these are simply the things I've learned in using javascript.
注意:我不是javascript专家,我没有正式的教育,这些只是我在使用javascript中学到的东西。
- If you define a variable outside a function, you can use it inside*
- 如果你在函数外定义一个变量,你可以在*内使用它
Using the same code I gave you, you could do something like this:
使用我给你的代码,你可以这样做:
$(document).ready(function() {
var arrObj = {};
//Notice, arrObj is now defined OUTSIDE of our form.onsubmit function
$('form').on('submit', function(e) {
e.preventDefault();
$(this).find('input:not(:submit)').each(function(i, el) {
el = $(el);
arrObj[el.attr('name')] = el.val();
});
console.log(arrObj);
});
$('button').on('click', function() {
console.log(arrObj);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<legend>form</legend>
<label>First
<input type="text" value="null" name="first" />
</label>
<label>Last
<input type="text" value="null" name="last" />
</label>
<label>Email
<input type="text" value="null" name="email" />
</label>
<input type="submit" value="submit" />
</fieldset>
</form>
<button>Click me and Check Console<small>*Must click submit button first</small></button>
- This goes up as far as you want it to.
- 只要你想,它就会上升。
Got a variable you defined outside the $(document).ready(...)
and you want to use it? Go ahead. Javascript don't care.
在$(document).ready(…)之外定义了一个变量,您想要使用它吗?去做吧。Javascript不关心。
- When in doubt, create another function that you can return from somewhere else, like so (this involves using
$.fn.extend()
to add a new method to every jquery object) - 当有疑问时,创建可以从其他地方返回的另一个函数(这涉及到使用$.fn.extend()向每个jquery对象添加新方法)
$.fn.extend({
formObject: function() {
var arrObj = {};
$(this).find('input:not(:submit)').each(function(i, el) {
el = $(el);
arrObj[el.attr('name')] = el.val();
});
return arrObj;
}
});
$(document).ready(function() {
$('button').on('click', function() {
alert('check console');
console.log($('form').formObject());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<legend>form</legend>
<label>First
<input type="text" value="null" name="first" />
</label>
<label>Last
<input type="text" value="null" name="last" />
</label>
<label>Email
<input type="text" value="null" name="email" />
</label>
</fieldset>
</form>
<button>Click Me</button>
These are not the only ways, and if I am honest I don't even think they're the best ways, but they're the fastest ways using what we already have.
这些不是唯一的方法,如果我诚实的话,我甚至不认为它们是最好的方法,但它们是使用我们已有的方法最快的方法。
#3
0
I don't understand why the submit button if the only need it go generate an object?
我不明白为什么提交按钮只需要生成一个对象?
So here is my try only to generate the output without arrays ...
这里我只尝试生成没有数组的输出…
function generate() {
var obj = {};
$('form input').not('[type="submit"]')
.each((index, input) => obj[input.name] = input.value);
$('#result').text(JSON.stringify(obj));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form>
<fieldset>
<legend>form</legend>
<label>First<input type="text" value="null" name="first"/></label>
<label>Last<input type="text" value="null" name="last"/></label>
<label>Email<input type="text" value="null" name="email"/></label>
<button onclick="generate()">Generate</button>
</fieldset>
</form>
<br>
<div id="result"></div>