Click to See Complete Forum and Search --> : how to add form text field dynamically?


smilecry
05-01-2003, 10:25 AM
Hi All:
I am working on a page which requires user input author names for a certain book. When there is more than three authors, the user will be able to click a button and new text fields will appear for additional entries.
I googled and found some sample codes but all of them solve the problem by rewriting the whole page on onclick event. My page is a quite complicated one, so that will not be very practical. Any other solutions? Thank you.
JY

khalidali63
05-01-2003, 10:36 AM
Originally posted by smilecry
Hi All:
all of them solve the problem by rewriting the whole page on onclick event. My page is a quite complicated one, so that will not be very practical. Any other solutions? Thank you.
JY

re-writing a page now adays is very wrong...
assign an id attribute to your form.

<form id="frm_1".....

then you can access is as follows

var frm = document.getElementById("frm_1");

now by using this reference you can add or delete elements..
add a text field
var textfield = document.createElement("input");
//by default input types are text
//if you want to add attributes
textfield.setAttribute("name","bookName");

The above techiniq will work all of the genereation 6+ browsers

smilecry
05-01-2003, 10:39 AM
Thanks! I will give it a try.

smilecry
05-01-2003, 11:33 AM
Khalid:
How to add new text filed to the form? Here is my code according to your explanation. I am really new to Javascript. Thank you :)
JY

<html>
<body>

<form id="frm_1">
input the firstname <input type = "text" name = "firstname"><br>
input the lastname <input type = "text" name = "lastname">
<input type = "button" value = "add new author" onclick=addAuthor()>

</form>

<script language="javascript">
function addAuthor()
{
//then you can access is as follows

var frm = document.getElementById("frm_1");

//now by using this reference you can add or delete elements..
//add a text field
var textfield = document.createElement("input");
//by default input types are text
//if you want to add attributes
textfield.setAttribute("firstname","lastname");

frm.???
}
</script>


</body>
</html>

khalidali63
05-01-2003, 12:01 PM
oops missed to type you need to add that to form as well to be proper.

frm.appendChild(textfield);

Then you can keep calling this method to add more fields..

smilecry
05-01-2003, 12:38 PM
Khalid:
Thanks a lot. You are really helpful.
Last questions :)

Is there a way to set the text before a textfield and define a change line in the function? I found that whenever I tried document.write('<br>'), it will turn me to a new page.
Is there any detailed online method index for javascript? I am just a spoiled user of Java. :)

Thanks again!
JY

khalidali63
05-01-2003, 02:44 PM
I love java..:-)..

you can try here.Its JavaScript1.5 reference

http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/

smilecry
05-01-2003, 03:02 PM
Thanks!