Welcome aboard Halim, I will tell you how . . . if you will listen to why this is a Very Bad Idea. :-) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 <!-- doctype all on one line, please --> Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Populate Form with Fields</title> </head>
<script type="text/javascript"> function populateFields() { var f=fields=''; var p = document.getElementById('name_holder'); var num = document.getElementById('num').value; // num == '' is only required, of course, by IE. // REPLACE THE ¦¦'s WITH PROPER VERTICAL PIPES if ((num == '') ¦¦ isNaN(num)) { p.innerHTML = ''; alert('Please enter a number for the number of passengers.'); return false; } // If it doesn't return, we're good, no need for an else.
for (i=0;i<num;i++) { var f='passenger_number_'+eval(i+1); // so it's not passenger 0 fields += '<label for="'+f+'">Passenger '+eval(i+1)+':<\/label> '+ '<input type="text" name="'+f+'" id="'+f+'" size="25" maxlength="100" value="'+ // Remove next line for practical application f+ '"><br>\n'; } p.innerHTML = fields; } </script>
<body> <h3>Create Fields</h3> <p>Press "Populate Names" if the fields don't appear when you tab out of the text field. "f" is placed in the field value for debugging.</p> <form action=""> <label for="num">How many Passengers?</label> <input type="text" name="num" id="num" onChange="populateFields();" size="4" maxlength="3" value=""> <input type="button" onClick="populateFields();" value="Populate Names"> <div id="name_holder"></div> <!-- id'ed container to hold the fields --> </form> </body> </html>
Why this is a bad idea: This method would be Javascript-dependent. If Javascript is disabled, you have nothing for your generated fields and lose business. You are best to do this server-side as a two-page process that collects num on the first page and displays fields on the next.
|