0

I design form to input firstName, lastName, fullName etc.. When I'm typing firtName and lastName I want to store firstName and lastName to variables called fName and lName using JavaScript. I tried to store those values but it didn't work,

   <form>
                <div class="form-group">
                        <label for="fName">Fist Name</label>
                        <input type="text" name="fName" id="id00" class="form-control"/>               
                </div>

                <div class="form-group">
                        <label for="lName">Last Name</label>
                        <input type="text" name="lName" id="id01" class="form-control"/>               
                </div>

                <div class="form-group">
                        <label for="fulName">Full Name</label>
                        <input type="text" name="fullName" id="id02" class="form-control"/>               
                </div>

        </form>
                <button type="button" onclick="myfunction()" class="btn btn-info">click me</button>
</div>
<!-- FOR THE JAVASCRIPT CONTENT-->
                <script lang="javascript">
                        var fName = document.getElementById('id00').innerHTML;
                        var lName = document.getElementById('id01').innerHTML;
                        var fullName = fName + " " + lName;
                function myfunction(){
                        document.getElementById('id02').innerHTML=fullName;
                }
                        </script>  
  • 2
    To get the value of `` elements you must access the `.value` property, not the `.innerHTML` one. I recommend you to follow a basic tutorial about HTML elements, their properties and how to interact with them. – Jorge Fuentes González Jan 04 '20 at 21:04
  • 2
    `fName & lName` should be inside of `myFunction`, and should be `.value` instead of `.innerHTML` – Christian Carrillo Jan 04 '20 at 21:04

1 Answers1

2

It's an input, so you need to use value property.

function myfunction(){
  var fName = document.getElementById('id00').value; // use .value instead of .innerHTML
  var lName = document.getElementById('id01').value;
  var fullName = fName + " " + lName;
  document.getElementById('id02').innerHTML=fullName;
}

A good explanation on the different ways to get the value from an input element are outlined in this Stackoverflow question.

pascalpuetz
  • 5,238
  • 1
  • 13
  • 26