Javascript 提交时将数据绑定到表单

Javascript 提交时将数据绑定到表单,javascript,forms,Javascript,Forms,我有一些表格: <form name="myForm" ... > 在提交时,我想在表单中添加几个键值对。在调用submit()函数之前,这些键值对不需要在表单中。我正在添加这样的配对: document.forms["myForm"][key] = value; 然而,这不起作用。它说我有一个意外的[。将数据绑定到表单的适当方式是什么 键、值对的示例: key = "PresentLevelsAssessment" + selected[i].id; value = selec

我有一些表格:

<form name="myForm" ... >
在提交时,我想在表单中添加几个键值对。在调用
submit()
函数之前,这些键值对不需要在表单中。我正在添加这样的配对:

document.forms["myForm"][key] = value;
然而,这不起作用。它说我有一个意外的
[
。将数据绑定到表单的适当方式是什么

键、值对的示例:

key = "PresentLevelsAssessment" + selected[i].id;
value = selected[i].getAttribute('data-type');
试试这个:

document.forms.myForm.elements.key.value = ****anyvalue****;

所以我不明白为什么它不起作用,所以我只是解决了它。我想根据是否选中某些选项来绑定数据。而不是在提交时绑定数据,而是在选中某个选项时将html写入表单

$('.check').on('click', function() {
    if ($(this).prop('checked')) {
        var html = '<div style="display:none" id="Info'+ $(this).attr('id') +'">' +
            '<input name="PresentLevelsAssessment'+ $(this).attr('id') +'" value="'+ $(this).attr('data-type') +'" />' +
            '<input name="PresentLevelsDate'+ $(this).attr('id') +'" value="'+ $(this).attr('data-date') +'" />' +
        '</div>';
        form.prepend(html);
    } else {
        $('#Info' + $(this).attr('id')).remove();
    };      
});
$('.check')。在('click',function()上{
if($(this.prop('checked')){
var html=''+
'' +
'' +
'';
form.prepend(html);
}否则{
$('#Info'+$(this.attr('id')).remove();
};      
});

这就是你的全部代码吗?看起来没问题。@scimonester还有一点,但这就是它的精神。我绝对遵循这里显示的标准。如果使用
document.forms[“myForm”].elements[key],你会得到什么.value=value;
?您能给我们一个填充键和值对的示例吗?不鼓励只使用代码的答案。除了提供功能代码外,最好解释原因和方式。
$('.check').on('click', function() {
    if ($(this).prop('checked')) {
        var html = '<div style="display:none" id="Info'+ $(this).attr('id') +'">' +
            '<input name="PresentLevelsAssessment'+ $(this).attr('id') +'" value="'+ $(this).attr('data-type') +'" />' +
            '<input name="PresentLevelsDate'+ $(this).attr('id') +'" value="'+ $(this).attr('data-date') +'" />' +
        '</div>';
        form.prepend(html);
    } else {
        $('#Info' + $(this).attr('id')).remove();
    };      
});