简体   繁体   English

无法将选项值放入隐藏字段

[英]Can't get the option value into a hidden field

I'm using a select with options and i would like to use a form to submit the text of an option field into a database.我正在使用带有选项的选择,并且我想使用表单将选项字段的文本提交到数据库中。

It's not working and I can't figure out why.它不起作用,我不知道为什么。 the p-element changes its value (i only used it for debugging, i actually don't need it) but the hidden field stays empty. p 元素改变了它的值(我只将它用于调试,我实际上不需要它)但隐藏字段保持为空。

can anybody help me out here?有人可以帮我吗?

 function GetSelectedText(){ var e = document.getElementById("kunde"); var result = e.options[e.selectedIndex].text; document.getElementById("title").textContent = result; }
 <select id="kunde" name="kunde" class="form-control" onchange="GetSelectedText()"> <option value="1">text for 1</option> <option value="2">text for 2</option> <option value="3">text for 3</option> </select> <p id="title">this text will be replaced</p> <input name="title" type="hidden" id="title" value="">

Since the hidden field is an input field, change textContent to value .由于隐藏字段是输入字段,因此将textContent更改为value

Also, you can't have more than one element with the SAME ID, so get rid of the P element since you don't need it anyway.此外,您不能拥有多个具有相同 ID 的元素,因此删除 P 元素,因为无论如何您都不需要它。

This is probably because your p element has the same ID as the input element.这可能是因为您的p元素与input元素具有相同的 ID。 HTML specifies that an ID must be unique. HTML 指定 ID 必须是唯一的。 Something like this would work:像这样的事情会起作用:

<p id="title">this text will be replaced</p>
<input name="title" type="hidden" id="titleInput" value=""> 

And the javascript:和 javascript:

// [...] rest of the function
document.getElementById("title").textContent = result;
document.getElementById("titleInput").value = result;

"textContent" has to be changed to "value". “textContent”必须更改为“value”。

Thanks for your help!谢谢你的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM