希望我无论如何都不会重复这个问题。但是我试图获得一个带有其名称值和字段值的表单部分,以作为单个concat字符串放置。就像
表格输入:
名:约翰
姓氏:Smith
字段5-10 ..等
字符串输出: FirstName = John&LastName = Smith&Field2 = Value2&Field_etc = Value_etc
我尝试过
var inputArray = $("form#form :input").each(function () {
var input = $(this);
console.log(input.attr('name') + ":" + input.val());
});
在console.log中正确输出测试值的方式为
firstName:John
lastName:Smith
但是我正在努力处理下一部分代码,这些代码将有助于console.log作为组合数组字符串记录。不确定这是 for循环还是有助于下一步的事情。
答案 0 :(得分:1)
在下面的代码中查看注释,也许这可以帮助您走上正轨...
这里最主要的好处是将提交数据存储为对象,然后使用$.param()将提交数据转换为url字符串。
// on form submit
$(document).on('submit', '#form', function(e) {
// prevent form default submit action
e.preventDefault();
// set empty submission object
let submission = {};
// for each of this form submit event target object entries as key/field
for (const [key, field] of Object.entries(e.target)) {
// if object entry (field) has a name attribute
if (field.name) {
// add name/value to submission object
submission[field.name] = field.value;
}
}
// convert submission object to url params string
var paramsStr = $.param( submission );
// log the string
console.log(paramsStr)
});
<form id="form">
<input name="firstName" value="John" type="text" />
<input name="lastName" value="Smith" type="text" />
<input name="userName" value="johnsmith" type="text" />
<button type="submit">Submit</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 1 :(得分:1)
浏览输入元素并连接名称和值:
const inputs = document.querySelectorAll('#form input')
let msg
inputs.forEach(inp => {
inp.onkeyup = () => {
msg = 'String Output: '
inputs.forEach(i => msg += `${i.name}=${i.value}&`)
console.clear()
console.log(`\r\n${msg.slice(0, -1)}\r\n\r\n`)
}
})
input {
display: block;
margin-bottom: 8px;
font:18px/1.2em Arial;
}
<form id='form'>
<input name='FirstName' placeholder='First Name' />
<input name='LastName' placeholder='Last Name' />
<input name='Example1' placeholder='Example 1' />
<input name='Example2' placeholder='Example 2' />
</form>