简体   繁体   中英

Javascript - Get Value from form by Get method

I can't print the value from the form's input at client.html to the table in server.html. It has to be written in Javascript and by using GET Method for form.

client.html:

<form action="server.html" method="get">
<p>
 Name: 
 <input type="text" id="txtname" name="txtname" />    
</p>
</form>

server.html:

<head>
<script type="text/javascript">

    function getUrlVars() {
        var vars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
            function (m, key, value) {
                vars[key] = value;
            });
        return vars;
    }
var name= unescape(getUrlVars()[document.getElementById("txtname")]);
document.getElementById("idname").innerHTML=name;
</script>
</head>
<body>
<table>
<tr>
    <td>Name:</td>
    <td id="idname"></td>
</tr>
</table>
<body>

There's a few things here:

You're trying to set the innerHTML of #idname to hoten.value , which is undefined.

getUrlVars()[docuemnt.getElementById("txtname")] also doesn't validate. You can simple use getUrlVars().txtname to get the query parameter.

You're also trying to set the value before the DOM has been processed - the JS cannot set the value of the element because it hasnt been placed on the page yet.

Fixing the errors and moving the JS to the end of the body tag fixes this:

<head>
</head>
<body>
<table>
  <tr>
    <td>Name:</td>
    <td id="idname"></td>
  </tr>
</table>
<script type="text/javascript">
  function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
      function (m, key, value) {
        vars[key] = value;
      });
    return vars;
  }

  var name= unescape(getUrlVars().txtname);
  document.getElementById("idname").innerHTML = name;
</script>
</body>

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