我的表单包含多个输入字段。例如:
<input type="number" class="attribute-class form-control" id="Size" min="1" max="99999" name="attribute[]">
<input type="number" class="attribute-class form-control" id="weight" min="1" max="99999" name="attribute[]">
现在我要创建一个数组,像这样的array[size => 10, weight=> 20]
那有可能吗? 到目前为止,我使用了在另一个主题中发现的该函数,但得到的是带有字段值的常规数组。
var attribute = $("input[name='attribute[]']").map(function(){
return $(this).val();}).get();
这样做的原因:我必须根据用户选择的产品类型在Ajax表单中加载其他输入字段,然后将字段名称和值存储在数据库中。这是我唯一想到的选择。
答案 0 :(得分:0)
您需要创建一个对象,而不是一个数组。您想将ID用作对象中的属性名称。
[Exception]
Notice: Use of undefined constant MCRYPT_RIJNDAEL_256 - assumed 'MCRYPT_RIJ
NDAEL_256' in /Applications/MAMP/htdocs/Magentooo/vendor/magento/framework/
Encryption/Encryptor.php on line 394
$("#x").click(function() {
var attribute = {};
$("input[name='attribute[]']").each((i, input) => attribute[input.id.toLowerCase()] = input.value);
console.log(JSON.stringify(attribute));
});
答案 1 :(得分:0)
似乎您想创建一个对象来存储输入字段中的值,
也许尝试这样的事情:
var myObject = {};
document.querySelectorAll("input[name='attribute[]']").forEach(element => {
myObject[element.id] = element.value
});
console.log(myObject); // <-- this should have your values in it now.
JavaScript没有关联数组,请使用非常相似的JavaScript对象。