简体   繁体   中英

Get the value from the form and insert that value in the table by using JavaScript

I have created simple form and table.. So I need to add values from the form. I have created the code but it is not working.

<html>
<body>
    <script>
        function clickFunction(){
            document.getElementByName('inputvalue').innerHTML = document.getElementByName('name');
            }
    </script>
    <form>
        Name: <input type="text" name="name">
        <input type="submit" value="Done" onclick="clickFunction()">
    </form>
    <table border="1">
        <tr><td>Data input: </td><td><label name="inputvalue" > null </label></td></tr>
    </table>
</body>
</html>

There are few things you have to fix first:

  1. It should be document.getElementsByName , you are missing a 's'.
  2. Since, the submit is in a form element. Once you click it, it will submit the form. So, you should stop it by using return false in the function.
  3. To get the value from the input box, you should add 'value' after document.getElementByName('name') . it should be document.getElementByName('name').value .
  4. I have added e.preventDefault . In-case, it tries to submit. In that case, there is a slight change in HTML.

    ... <input type="submit" value="Done" onclick="clickFunction(event)"> ...

The corrected source code: https://jsfiddle.net/gy03xz4b/4/

HTML is fine, the js will change a bit:

 function clickFunction() {
   document.getElementsByName('inputvalue')[0].innerHTML = document.getElementsByName('name')[0].value;
   return false;
 }

Hope that helps!

Refers:

  1. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName

  2. http://www.irt.org/script/155.htm (What does 'return false' do?)

  3. https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault (e.preventDefault)

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