0

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>
James Z
  • 12,209
  • 10
  • 24
  • 44
  • 1
    I think this question could help you [How to get the value from the GET parameters?](https://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters) – 3Dos Oct 21 '17 at 08:34
  • 1
    `getUrlVars()[document.getElementById("txtname")]` will always access `vars["[object HTMLInputElement]"]`. Did you mean `getUrlVars()[document.getElementById("txtname").value]`? – Sebastian Simon Oct 21 '17 at 08:36

1 Answers1

0

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>
Jamie McElwain
  • 462
  • 4
  • 12