javascriptdomdom-eventsnodelistcreatetextnode

How do I select an element value from an Node List?


I need help in an exercise. I have to create a new element with a specific TextNode. This TextNode is the value from two inputs. FirstName and LastName that creat a new paragraph with that values when I click the submit button. I tried do a lot of things without sucess. The result doesn't show.

This is the snippet code:

(function() {
    'use strict'

    var $form = document.getElementById('form1');
    var $names = document.getElementsByTagName('input');
    var $button = document.getElementById('press');

    $button.addEventListener('click', getValueName);

    function getValueName() {
        for(var i = 0; i<$names.length; i++) { 
            $names[i]; 
        } 
    
        var output=document.createTextNode('$names.value[0]' +
        '$names.value[1]' ); 
        var novop=document.createElement('p');
        novop.appendChild(output); 
        $form.appendChild(novop); 
    }
})();
<form id="form1" onsubmit="getFormvalue()">
    First name: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>
    <button id="press" type="submit" value="Submit">Submit</button>
</form>


Solution

  • What you are doing wrong is getting value from array of values

    names.value[0] + names.value[1]

    while the array is of names

    names[0].value + names[1].value

    function getFormvalue() {
    
      var formData = document.getElementsByTagName('body')[0];
      var names = document.getElementsByTagName('input');
      var output = document.createTextNode(names[0].value + names[1].value);
      var novop = document.createElement('p');
      novop.appendChild(output);
      formData.appendChild(novop);
    }
    <body>
      First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br>
      <button id="press" type="submit" value="Submit" onclick="getFormvalue()">Submit</button>
    </body>