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 3 of 3
  1. #1
    New Coder
    Join Date
    May 2007
    Posts
    56
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Dynamic textbox creation like on trackvia

    I am trying to make a php page that has a button that when clicked will generate html elements. What I am trying to do is very similar to trackvia.com but perhaps a bit simpler.

    I have a form and then within the form I have the following javascript code to create an html element.

    <script language="javascript">

    function changeIt()
    {
    var i = 1;
    my_div.innerHTML = my_div.innerHTML +
    "<br>Block<input type='text' name='mytext'+ size='2'>Acres<input type='text' name='acres'+i size='4'>"
    }

    </script>


    This part works, except that if I need to create multiple elements the values are dropped after clicking the button to create a second textbox when I try and POST the values after the form button (a different standard PHP form button.

    Can anyone point me in the right direction?

  • #2
    Regular Coder
    Join Date
    Jul 2007
    Location
    UK
    Posts
    223
    Thanks
    0
    Thanked 14 Times in 14 Posts
    This is a Javascript question and should be moved to the javascript forum.

    Your function has several things wrong with it;
    "i" is never incremented so every time you call the function it will alwys be 1.
    You aren't adding "i" to the variable name because I think you might be trying to use php syntax in javascript!
    I don't think firefox likes you adding form elements in this way, hence you are seeing the values dropped (it works in IE7 though!). I don't advocate the use of innerHTML and always use DOM methods when adding elements to pages myself.

    The simplist way to fix your script is this;
    Code:
    var i = 1; //define i outside the function so it is a global variable.
    function changeIt()
    {
     var my_div=document.getElementById("my_div");
     
     var newdiv = document.createElement("div");
     newdiv.innerHTML = "<br>Block<input type='text' name='mytext"+i+"' size='2'>Acres<input type='text' name='acres"+i+"' size='4'>";
     my_div.appendChild(newdiv);
     i++; //increment i after we've used it.
    }
    However I think you should learn about the DOM methods createElement, appendChild, etc and use these instead of innerHTML.

  • #3
    New Coder
    Join Date
    May 2007
    Posts
    56
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you so much for the help. I really appreciate it (especially the help with the code). I will look into all of this.


  •  

    Posting Permissions

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