How To Append Value To An Array In JavaScript

How To Add Value To An Array Using Javascript

Add Element To An Array Using JavaScript



In This Javascript Tutorial we will see How To Add Element To An Array From Input Text Field Using Push Method Array In JS Using Netbeans Editor .




Project Source Code:

<!DOCTYPE html>

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="windows-1252">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        
        <input type="text" name="text" id="inputText"/>
        <button onclick="pushData();">Show</button>
        <p id="pText"></p>
        
        <script>
            
            // create an array
            var myArr = ["A","B","C","D"];
            
            function pushData()
            {
                // get value from the input text
                var inputText = document.getElementById('inputText').value;
                
                // append data to the array
                myArr.push(inputText);
                
                var pval = "";
                
                for(i = 0; i < myArr.length; i++)
                {
                    pval = pval + myArr[i] + "<br/>";
                }
                
                // display array data
                document.getElementById('pText').innerHTML = pval;
            }
            
        </script>

    </body>
</html>




Share this

Related Posts

Previous
Next Post »

2 comments

comments
15 juin 2018 à 17:52 delete

please how do i get this output data displayed on a different page

Reply
avatar
6 avril 2019 à 06:20 delete

How do i get this output by only clicking on a button and no input text??

Reply
avatar