我在用户从另一个选择元素做出选择后动态创建一个 HTML 选择元素。然而,用于检查表单的 PHP 脚本无法识别新元素并指示它为空。
这里是片段:
some.js:
if(document.getElementById(firstselect).value=='somvalue'){
document.getElementById(gamsDiv).removeChild(gamsElem);
gamsElem = document.createElement("select");
gamsElem.id = "FacilityGamsId";
gamsElem.name = "FacilityGamsId";
gamsElem.setAttribute("onChange", "updateHidden(this);makeUpdateRequest(arguments[0],this)");
opt = document.createElement("option");
opt.text="Select one ";
opt.value=0;
gamsElem.options.add(opt);
.....some other stuff
.....
document.getElementById(gamsDiv).appendChild(gamsElem);
}
PHP脚本:
if($_POST){
var_dump($_POST['FacilityGamsId'];
}
result: null
服务器发布操作是否有任何原因无法从 JS 脚本中识别我的任何动态 HTML 元素。如果我检查/检查新创建的元素,名称和 ID 完全相同。
它不会添加到存储在浏览器 DOM 中的表单中。
这家伙试图做同样的事情:创建的动态元素未发布
一个解决方案是在服务器端构建动态表单——如果它真的需要在客户端,我认为除了 DOM 之外,您还需要操作表单(存储在
document.forms
中)。
这里:
gamsElem.options.add(opt);
add 是 select 元素接口 的方法,而不是 options(它是一个 HTMLElement Collection,没有 add 方法)。所以:
gamsElem.add(opt);
应该解决这个问题。
Note that gamsElem.add(opt); does not work in Mozilla firefox 6 so I reverted to my old code of gamsElem.options.add(opt).
和:
gamsElem.setAttribute("onChange",
"updateHidden(this);makeUpdateRequest(arguments[0],this)");
会更好:
gamsElem.onchange = function() {
updateHidden(this);
makeUpdateRequest(arguments[0], this);
};
虽然我不知道arguments[0]应该参考什么。
这是通常如何完成的(虽然按钮会调用一个函数而不是有一段内联代码,我这样做只是为了方便):
<form action="">
<div id="div0">
<select id="sel0" name="sel0">
<option>option 0
</select>
<input type="submit">
</div>
</form>
<button onclick="
var div = document.getElementById('div0');
var sel = document.getElementById('sel0');
div.removeChild(sel);
sel = document.createElement('select');
sel.id = 'sel1';
sel.name = 'sel1';
sel.onchange = function(){alert(this.value);};
sel.options[0] = new Option('Select one', '0');
sel.options[1] = new Option('Select two', '1');
div.appendChild(sel);
">Replace select</button>
需要第二个选项才能触发 onchange 侦听器。
如果你想用另一个元素替换一个元素,创建新元素然后替换旧元素:
<button onclick="
var oldSel = document.getElementById('sel0');
var sel = document.createElement('select');
sel.id = 'sel1';
sel.name = 'sel1';
sel.onchange = function(){alert(this.value);};
sel.options[0] = new Option('Select one', '0');
sel.options[1] = new Option('Select two', '1');
oldSel.parentNode.replaceChild(sel, oldSel);
">Replace select</button>
或者您可以只替换选项(将 select 的 options.length 设置为零并添加新选项)。
你必须在你的 FORM 标签中添加一个新元素
在 DOM 准备好后运行这段代码,最好是 jquery 中的 $.ready()。
并在 div 名称周围加上引号(“gamsDiv”)