Javascript动态生成的选择菜单,在POST

时间:2016-11-18 22:13:38

标签: javascript php html forms

这个话题并不新鲜。事实上,我写这段代码直接复制接受的答案frmo另一个线程。但是我的代码仍然不起作用,可能是因为情况略有不同。

我有一个网页(由php生成),其中包含my_form表单,以及页面上其他地方的另一种表单。下面的函数showAddRespPersonMenu应该生成一个员工的下拉菜单,分配到一个作业,在一个列出数百个作业的页面上。 (这就是我动态创建选择菜单的原因:避免让网页浏览器卡住100个不必要的隐藏或可见选择菜单,每个选项包含100名员工可供选择。)因此用户想要修改一些100个作业,我通过单击作业 - 运行showAddRespPersonMenu(theRespId)函数动态生成仅供用户感兴趣的作业的员工菜单,其中提交的theRespId是作业的ID。

以下代码在页面上可视化,在页面上生成选择菜单。但它没有在php POST输入中显示。执行命令var_dump($ _ POST)显示所有静态表单字段及其值(形式为my_form),但不显示动态生成的选择菜单。有问题的div位于my_form的标记和标记之间。问题仍然是动态生成的选择菜单不会以my_form形式分配,因此提交my_form不会发送这些字段吗?一个谜,因为在另一个线程中,几乎相同的代码(显然只在页面上有一个表单)被接受为功能。

var theSaveButtonHTML  = \'<a href="#" onclick="document.my_form.submit(); return false;"><img src="pics/save.png"></a>\';

function showAddRespPersonMenu(theRespId) {
var theDiv = document.getElementById(\'addRespPersonDiv\' + theRespId);
theDiv.innerHTML = "";
// Create and append a select menu
var selectMenu = document.createElement("select");
selectMenu.id = \'addPrimaryPersonMenu\' + theRespId;
theDiv.appendChild(selectMenu);
// Create and append options into the menu
for (var i = 0; i < personIdsArray.length; i++) {
var thisOption    = document.createElement("option");
thisOption.value = personIdsArray[i];
thisOption.text  = personNamesArray[i];
selectMenu.appendChild(thisOption);
}
document.getElementById(\'saveAddedPersonDiv\' + theRespId).innerHTML = theSaveButtonHTML;
document.getElementById(\'addUsersToResps\').value += \':\' + theRespId;
}

3 个答案:

答案 0 :(得分:1)

我认为您需要将name属性添加到selectMenu节点。

selectMenu.setAttribute('name', 'SOME_NAME');

有关setAttribute的更多信息。

答案 1 :(得分:0)

确实缺少名称参数......这是一个好点!

不幸的是,在appendChild命令之前添加此代码行后问题仍然存在:

selectMenu.setAttribute(\'name\', \'add_rsp_person_primary_\' + theRespId);

我也试过这个,结果同样糟糕:

selectMenu.name = \'add_rsp_person_primary_\' + theRespId;

解决这个谜团会很好干净。同时,我必须用一些口香糖解决这个问题,可能会在动态生成的选择菜单上触发onChange功能,将用户选择附加到静态隐藏文本字段中,该字段将包含与用户一样多的选择菜单。制作,以及哪个php将在POST输入中。

答案 2 :(得分:0)

这就是诀窍,功能正常......但这确实是一个技巧,而不是对所提出问题的实际干净解决方案:

我动态地将选择菜单创建为innerHTML,而不是createElement。这允许我轻松地将onChange触发器添加到选择菜单(这也可能与createElement一起使用,我只是不知道它的语法):

onChange="updatePrimaryPersonChoice(\' + theRespId + \', this.options[this.selectedIndex].value);"

然后触发的函数将用户选择保存到静态隐藏文本字段中,php将在POST输入中看到:

function updatePrimaryPersonChoice(theRespId, thePersonId) {
// destroy from a hidden submit field any choice which the user may have done earlier
document.getElementById(\'add1stPersonsToResps\').value = document.getElementById(\'add1stPersonsToResps\').value.replace(\':\' + theRespId + \'/\', \':0/\');
// append into a hidden submit field the choice which the user has made now
document.getElementById(\'add1stPersonsToResps\').value += \':\' + theRespId + \'/\' + thePersonId;
}