简体   繁体   中英

How to add more input tag value with JavaScript for Forms when submitting

I have a page which may has about more than 1 form like below.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Page</title>
    </head>
    <body>
        <form id="form1">
            <input type="text" name="fname1" />
            <input type="submit" />
        </form>
        <form id="form2">
            <input type="text"  name="fname2"/>
            <input type="submit" />
        </form>
        <form id="form3">
            <input type="text" name="fname3" />
            <input type="submit" />
        </form>

        <script>
             var formsx = document.forms.length; 
             for (i= 0; i < formsx; i++) {
                 form = document.forms[i];
                 form.addEventListener("submit", function(evt){
               /// alert("form action");
               });
             }
        </script>
    </body>
</html>

I would like to add one hidden value () whenever user submits form with Classic Javascript. If any of form submit, the new hidden value should be added. So at the backend, the POST request will have two "name" and "hidden" parameters values instead of one according to above script. I just want to code with JavaScript only. Please let me know how can I do that, thanks in advance.

You just need to use document.createElement and appendChild :

form.addEventListener("submit", function(evt){
  var input = document.createElement("input");
  input.setAttribute("type", "hidden");
  input.setAttribute("name", newName);
  input.setAttribute("value", "value");
  form.appendChild(input);
  return true;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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