Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - How to add a new hidden input fields to the form on submit

I want to pass certain hidden parameters in a request when some conditions are met.

For example I want to pass these if this condition is true:

<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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The document.forms object is a collection of all <form> elements in the page. It has numeric indexes, and named items. The named items correspond to a name attribute of each <form>.

var theForm = document.forms['detParameterForm'];

To make appending data easier, you can create a function which adds data for a given form.

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...