PDA

View Full Version : Dynamically add input field to page



mtran
06-12-2008, 03:23 PM
Hi, I have the following example form in which I want if users click on the checkbox [NOT the submit button], the input text field will be added right away somewhere on the same page, then everything will be submitted when users click on the Submit button.

Right now when I clicked, the page refreshes.
The real list of checkboxes is pretty long, about 30 items. I'm not sure what is a good way of doing this.

Thanks for help!



<form name="contact">
<input type="checkbox" name="Distributor" value="MSN" onclick="generate_formId();" /> MSN<br />
<input type="checkbox" name="Distributor" value="Yahoo" onclick="generate_formId();" /> Yahoo!<br />
<input type="checkbox" name="Distributor" value="Google" /> Google<br /><br />

<script type="text/javascript">

function generate_formId(){
var Distributor_id = new Array()
Distributor_id[0]="http://www.msn.com";
Distributor_id[1]="http://www.yahoo.com";
Distributor_id[2]="http://www.google.com";

for (var i=0; i < document.contact.Distributor.length; i++){
if (document.contact.Distributor[i].checked){
document.write('<input name="form_id" type="text" value="'+Distributor_id[i]+'" />');}}
//return false;
}
</script>

<input type="submit" value="submit" onclick="generate_formId();" />
</form>

Nile
06-13-2008, 02:58 AM
It's because of your document.write. Here, try this:



<form name="contact">
<div id="finput"></div>
<input type="checkbox" name="Distributor" value="MSN" onclick="generate_formId();" /> MSN<br />
<input type="checkbox" name="Distributor" value="Yahoo" onclick="generate_formId();" /> Yahoo!<br />
<input type="checkbox" name="Distributor" value="Google" /> Google<br /><br />
<input type="submit" value="submit" onclick="generate_formId();" />
</form>

<script type="text/javascript">

function generate_formId(){
var Distributor_id = new Array()
Distributor_id[0]="http://www.msn.com";
Distributor_id[1]="http://www.yahoo.com";
Distributor_id[2]="http://www.google.com";

for (var i=0; i < document.contact.Distributor.length; i++){
if (document.contact.Distributor[i].checked){
document.getElementById('finput').innerHTML='<input name="form_id" type="text" value="'+Distributor_id[i]+'" />';}}
//return false;
}
</script>


Should work. :)