Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I add form inputs to dynamically created divs? 2

Status
Not open for further replies.

jfarmerjr

Programmer
Mar 10, 2010
21
US
Here's the function I have to create a div with some text inputs in it. I believe the use of innerHTML has been deprecated (or maybe just frowned upon) so I was wondering how I could do it with createElement or something, I would also like to put the inputs into an array for each, e.g. Ename[], Eposition[], so that multiple divs just put the same inputs into an array.

Here's the function I have so far:

Code:
    function createDiv()
    {
        var divTag = document.createElement("div");
        var mydiv = document.getElementById("empBigDiv");
        
        divTag.setAttribute("align","center");
        
        divTag.style.margin = "0px auto";
        
        divTag.className ="dynamicDiv";
        
        divTag.innerHTML = "<label for=\"Ename\">Name: <input type=\"text\" style=\"display: inline;\" name=\"Ename\" size=\"20\"></label>  Address: <input type=\"text\" style=\"display: inline;\" name=\"Eaddress\" size=\"20\"> Position: <input type=\"text\" style=\"display: inline;\" name=\"Eposition\" size=\"20\"><br>";
		  divTag.innerHTML += "Reason for Leaving: <input type=\"text\" name=\"Ereason\" size=\"20\">  Employed From: <input type=\"text\" name=\"Efrom\" size=\"20\"> Employed To: <input type=\"text\" name=\"Eto\" size=\"20\"><br>";
        
        mydiv.appendChild(divTag);
    }

Any thoughts?
 
You have to use write or writeln to use JS to write content to the browser.

Not sure why you beleive innerHTML is bad, w3schools doesn't think so...



"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

Google Rank Extractor -> Perl beta with FusionCharts
 
I'm not really a detractor of the innerHTML, in fact I find it to be very useful, and well supported, however I understand why most people think its not a correct way to output text to the browser.

With that said, I disagree, that writing to the browser should be only done with write or wirteln, unless you now exactly what you are doing with those 2, and understand what it is they do, you are going to be in a world of problems. Using write after the webpage has loaded will cause it to vanish and be replaced with whatever you directed it to write out.

To the problem at hand, if you want to use the create element functions something like this should let you create an element:

Code:
function buildInput(){
var Inpname=prompt("Name your new element");
var Inpvalue=prompt("Assing a value to your element");
 var myDiv=document.getElementById('dest');
 var myInput=document.createElement('input');
 myInput.name=Inpname;
 myInput.type="text";
 myInput.value=Inpvalue;
 myDiv.appendChild(myInput);
 }


After creating the element, you can append it to whichever other element you need by using that element's appendChild method.

This is technically the correct way of adding elements to the DOM.
Personally I still prefer innerHTML but to each their own.


NOTE: w3schools is now starting to fall prey of outdated coding practices, and ill-conceived and unexplained suggestions. I suggest you don't take it too seriously. Most notably their usage of the write() functions should be completely removed and disregarded.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
oh, nice one Phil.

I've been so used to using W3C & W3Schools as my bible, i never realised it was out of date and becoming defunc.


"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

Google Rank Extractor -> Perl beta with FusionCharts
 
Alright, I think I'm going to stick with the innerhtml since I can't get the other way to work quite how I want it to. How can I make it so that the inputs in the innerHTML are created as arrays, or how can I add a counter to add a number to the end of each one? For example, if I created 2 divs with that function, I would have Ename[0] and Ename[1] OR Ename1 and Ename2
 
That kind of depends on how you are doing this.

Assuming you are calling the function at different times and you want to make your new elements consecutive to the last ones you could set up a number or counter variable that is global, and alter it each time you create an element.


Code:
<script ...>
[red]var counter=0;[/red][green]\\This counter will be global[/green]
function buildInput(){
 var myDiv=document.getElementById('dest');
 var myInput=document.createElement('input');
 myInput.name="thename" + counter;
[green]\\or myInput.name="thename[" + counter + "]";[/green]
 [blue]counter++;[/blue]
 myInput.type="text";
 myInput.value=Inpvalue;
 myDiv.appendChild(myInput);
 }

</script>



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Still having some trouble with it, the function is called from a button. It's part of a web application, each div that's called is for a previous employer. Here's what I have now:

Code:
var counter=0;

    function createDiv()
    {
        var divTag = document.createElement("div");
        var mydiv = document.getElementById("empBigDiv");
        
        divTag.setAttribute("align","center");
        
        divTag.style.margin = "0px auto";
        
        divTag.className ="dynamicDiv";
        
        divTag.innerHTML = "<label for=\"Ename\">Name: <input type=\"text\" style=\"display: inline;\" name=\"Ename[" + counter + "]\" size=\"20\"></label>  Address: <input type=\"text\" style=\"display: inline;\" name=\"Eaddress[" + counter + "]\" size=\"20\"> Position: <input type=\"text\" style=\"display: inline;\" name=\"Eposition[" + counter + "]\" size=\"20\"><br>";
		  divTag.innerHTML += "Reason for Leaving: <input type=\"text\" name=\"Ereason[" + counter + "]\" size=\"20\">  Employed From: <input type=\"text\" name=\"Efrom[" + counter + "]\" size=\"20\"> Employed To: <input type=\"text\" name=\"Eto[" + counter + "]\" size=\"20\"><br>";
        counter++;
        mydiv.appendChild(divTag);
    }

But I'm still not getting an array, and the values aren't being passed.
 
That creates a div with inputs each with a different number. Each time the function is called, a DIV is created, and its innerHTML modified to contain the string you have, and each time the input elements inside get an increasing number.
Ename[0]
Ename[1]
Ename[2]
etc... Each input becomes and array.


The real question then is: Where is this passed to? Where are you receiving the data? What exactly are you attempting to do with it.

If I use your code and submit it using a form to a server side script page, I get an array with the values, each input is an array on its own with the passed values.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
on small note from my point of view.

use single quotes when passing a value to innerHTML, then you won't need to escape all those other double quotes in the HTML!



"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"

Google Rank Extractor -> Perl beta with FusionCharts
 
I'm submitting them via a form, then trying to view the data with php, but I'm not seeing the data I enter into the inputs. Is the data saved as a multi-demensional array in $_POST? ($_POST[Ename[]] maybe?) For all the other pages of the application (which are just simple forms) I place all the data that's captured into hidden inputs and pass them forward using this code:

Code:
<?php
  foreach($_POST as $key=>$value){
    if ($key!="next"){
      $value=htmlentities(stripslashes(strip_tags($value)));
      echo "\t<input type=\"hidden\" name=\"$key\" value=\"$value\">\n";
    }
  }
?>

The reason I wanted them in an array instead of just string.counter format is I thought it'd be easier to determine how many were created when I get ready to stuff all the info into a database.
 
Yes they become arrays within arrays.

If you do:

Code:
echo "<pre>";
print_r($_POST);
echo "</pre>";

You should have something that look like this provided everything is within a form.

Code:
Array
(
    [Ename] => Array
        (
            [0] => Peter Jackson
            [1] => John Smith
            [2] => Marie Johnson
        )

    [Eaddress] => Array
        (
            [0] => somehwere
            [1] => Elsewhere
            [2] => Not here 
        )

    [Eposition] => Array
        (
            [0] => Manager
            [1] => Assistant
            [2] => Secreatary
        )

    [Ereason] => Array
        (
            [0] => Terminated
            [1] => no Raise Given
            [2] => Maternity
        )

    [Efrom] => Array
        (
            [0] => 1999
            [1] => 2005
            [2] => 2000
        )

    [Eto] => Array
        (
            [0] => 2007
            [1] => 2010
            [2] => 2010
        )

    [svp] => Send Values
)

Each name is an array onto itself. so Ename[1] would have the second name provided from the second div created by your code.

Again his all assumes all your new divs are inside the same form.


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
You're right, it works great! Thanks a bunch for your help, and your patience.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top