Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Nov 2013
    Posts
    6
    Thanks
    0
    Thanked 1 Time in 1 Post

    using push with arrays?

    I have the following in the <head> of my html:

    Code:
    <script language="javascript" type="text/javascript">
    var xvalues = new Array();
    <!--
    function AddX()
    {
    xvalues.push (document.getElementById("xvalue"));
    }
    -->
    </script>
    In the body of the page I have a text input box with the id "xvalue" and an "add" button which calls the function "AddX()".
    For some reason whenever the button is pushed it changes every value in the xvalues array to whatever is in the textbox, rather than just the last value.
    Am I doing something wrong? Does it have to do with where I define the array?
    Any help is appreciated.

  • #2
    Regular Coder
    Join Date
    Aug 2010
    Posts
    945
    Thanks
    19
    Thanked 205 Times in 203 Posts
    Code:
     
     <!DOCTYPE html>
    <html>
    <head>
     <title></title>
     <meta charset="utf-8" > 
     <script>
    var xvalues = new Array();
    function AddX(){
     xvalues.push (document.getElementById("xvalue").value);
    }
    </script> 
    </head>
    <body>
    <input id="xvalue"></inpot>
    <button onclick="AddX();alert(xvalues);xvalue.value='';">click</button>  
    </body>
    </html>

  • #3
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    3,762
    Thanks
    23
    Thanked 546 Times in 545 Posts
    This is incomplete
    Code:
    document.getElementById("xvalue")
    I take it you want what typed into the text box (id = "xvalue") to be pushed into the array. Use
    Code:
    document.getElementById("xvalue").value
    and move all of your javascript to the bottom of your HTML, just before the body tag.
    Evolution - The non-random survival of random variants.

  • #4
    New to the CF scene
    Join Date
    Nov 2013
    Posts
    6
    Thanks
    0
    Thanked 1 Time in 1 Post
    OK I had to change a couple of things and have it working now. Thanks a lot for your replies.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •