Jump to content

[SOLVED] adding textboxes: onclick="addboxes()"


itazev

Recommended Posts

Hey ya!

 

I am looking for a way to put on the page body text boxes (<input type="text">) as many as the user clicks the button "add field".

 

I tried document.write() function but it erases all the page content and then add the field.

 

sketch:

<form ... >
   <input type="text" name="field1"><br>
   <input type="text" name="field2"><br>
   <input type="text" name="field3"><br>
    .
    .
    .
   <!-- and so on -->
   <input type="button" value="Add field"><br>
</form>

 

I appreciate any help

Link to comment
https://forums.phpfreaks.com/topic/48868-solved-adding-textboxes-onclickaddboxes/
Share on other sites

<form ... >
   <input type="text" name="field1"><br>
   <input type="text" name="field2"><br>
   <input type="text" name="field3"><br>
   <div id="extra_field">
       <!--Your extra filed will goes here-->
    </div>
   <input type="button" value="Add field" onclick="addfield();"><br>
</form>

 

<script language="javascript" type="text/javascript>
var current_field = 3;
function addfield()
{
    current_field ++;
    document.getElementById("extra_field").innerHTML += "<input type=\"text\" name=\"field\"" + current_field + " /><br />";
}
</script>

 

Never try before, but should works. Hope this help you

There is just a problem: the current_field variable never apperas on the POST or GET string.

Something like

processform.php?field=aaaa?field=bbbb?field=cccc?field=dddd

 

 

<script language="javascript" type="text/javascript>
var current_field = 3;
function addfield()
{
    current_field ++;
    document.getElementById("extra_field").innerHTML += "<input type=\"text\" name=\"field\"" + current_field + " /><br />";
}
</script>

 

appreciate your time!

If you are using multiple fields that you do not know how much user will need, I will suggest you this method:

 

function addfield()
{
    document.getElementById("extra_field").innerHTML += "<input type=\"text\" name=\"fields[]\" /><br />";
}

 

Put your input field name with a brackets indicates it as an array.

 

So in your php file:

 

<?php
if(sizeof($_POST['fields'])){
    //$_POST['fields'] refers as an array. Get all the data then do what you want.
    foreach($_POST['fields'] as $str){
        echo $str . "<br />";
    }
}
?>

 

Sorry for late reply. Busy these few days.  ;)

 

Hope this help you.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.