简体   繁体   English

如何在HTML中使用Java脚本替换动态隐藏值

[英]How to replace the hidden value dynmaicaly using java script in html

<form method="post" name="test" id="test">
<input type="hidden" name="listname" value="qpaustin" />
<select name="customCity" id="customCity" onchange="javascript:onChangeHiddenValue(this.value);"> 
<option value="qpneworleans" >qpneworleans</option>
<option selected="selected" id="listSelectionActiveOption" value="qpnewyork" >qpnewyork</option>
<option value="qporangecounty">qporangecounty</option>
<option value="qporlando">qporlando</option>
</select>
</form>
<script type="text/javascript">
function onChangeHiddenValue(cityName)
{

    alert(document.getElementById('customCity').value);

}
</script>

I need to change the hidden value "listname" dynamically using javascript. 我需要使用javascript动态更改隐藏值“ listname”。

For example, currently the value of listname is qpaustin. 例如,当前listname的值为qpaustin。 But when i change the value to qpneworleans the "listname" value should be replaced to qpneworleans . 但是当我将值更改为qpneworleans时,应将“ listname”值替换为qpneworleans。

How to do this. 这个怎么做。

Kindly advice. 好心的建议。 Thanks in advance 提前致谢

A few comments: 一些评论:

  1. The onchange event should be bound to the select element, no to the option s. onchange事件应绑定到select元素,否应绑定到option
  2. Give your form a name, that will make the programmatic access easier, eg document.forms['formName'] 给您的表单起一个名字,这将使编程访问更加容易,例如document.forms['formName']

For example: 例如:

<form method="post" name="form1">
  <input type="hidden" name="listname" value="qpaustin" />
  <select name="customCity" onchange="onChangeHiddenValue(this.value);"> 
    <option value="qpneworleans">qpneworleans</option>
    <option selected="selected" value="qpnewyork">qpnewyork</option>
    <option value="qporangecounty">qporangecounty</option>
    <option value="qporlando" >qporlando</option>
  </select>
</form>

<script type="text/javascript">
function onChangeHiddenValue(cityName) {
  // DOM2 standard way to access forms and elements
  document.forms['form1'].elements['listname'].value = cityName;
}
</script>

Check the above example here . 此处检查以上示例。

Its better if you can give an id to the hidden element. 如果您可以给隐藏元素一个id更好。 Something like 就像是

<input type="hidden" id="listname" name="listname" value="qpaustin" />

and your javascript to assign value to that element will be 和您的javascript以将值分配给该元素将是

document.getElementById("listname").value = cityName;

Apart from the solution that Rahul has provided you can also try out the following. 除了Rahul提供的解决方案之外,您还可以尝试以下方法。

document.test.listname.value = cityName;

In Javascript you can refer to form elements by their names. 在Javascript中,您可以通过表单元素的名称来引用表单元素。

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

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