如何在提交时向表单添加新的隐藏输入字段

Doc*_*day 11 javascript

我希望在满足某些条件时在请求中传递某些隐藏参数.

例如,如果满足以下条件,我想传递这些:

<script type="text/javascript"> 
 function checkClosureLevel()
 {
    var openLevel = document.getElementById('openLevel');
    var phyCompLevel = document.getElementById('phyCompLevel');
    var finCompLevel = document.getElementById('finCompLevel');

    if (openLevel.checked) { 
      //PASS HIDDEN FORM VARIABLES HERE AND SUBMIT FORM 
    }
 }
</script>

<form action="process.det_details" method="post" name="detParameterForm">
  <fieldset class="det">
    <legend>Closure Level</legend>
    <input type="checkbox" name="openLevel" >Open</input><br/>
    <input type="checkbox" name="phyCompLevel" >Physically Complete</input>
    <br/>
    <input type="checkbox" name="finCompLevel" >Financially Complete</input>
  </fieldset>
</form>
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 47

document.forms对象是<form>页面中所有元素的集合.它有数字索引和命名项.命名项对应于name每个的属性<form>.

var theForm = document.forms['detParameterForm'];
Run Code Online (Sandbox Code Playgroud)

为了使附加数据更容易,您可以创建一个为给定表单添加数据的函数.

function addHidden(theForm, key, value) {
    // Create a hidden input element, and append it to the form:
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key; // 'the key/name of the attribute/field that is sent to the server
    input.value = value;
    theForm.appendChild(input);
}

// Form reference:
var theForm = document.forms['detParameterForm'];

// Add data:
addHidden(theForm, 'key-one', 'value');
addHidden(theForm, 'another', 'meow');
addHidden(theForm, 'foobarz', 'baws');

// Submit the form:
theForm.submit();
Run Code Online (Sandbox Code Playgroud)