最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - dynamically add fields to form and access the values from php script - Stack Overflow

programmeradmin1浏览0评论

I am adding text fields to the form dynamically, but now I need to be able to store these values into a mysql database. I am able to do this if there are no dynamically created fields. Here is the code -

<!DOCTYPE HTML>
<html>
    <head>  
        <title> Company Value form </title>
        <script language = "javascript">
            function addTextField(){
                var element = document.createElement("input");
                element.setAttribute("name", "i");
                element.setAttribute("value", "sample value");
                element.setAttribute("size", 30);

                var twitter = document.getElementById("twitterusernames");
                twitter.appendChild(element);

            }

        </script>
    </head>

    <body>
        <h1> Enter the values </h1>
        <form method = "post" name = "config_form" action = "message.php">
            <table border = "1px" >
                <tr> <td>
                    <b> Twitter </b> <br/> <br/>
                    FeatureId: <input type = "text" name = "FeatureId"> <br/>
                    Image: <input type = "text" name = "Image"> <br/>
                    LabelEn: <input type = "text" name = "LabelEn"> <br/>
                    LabelFr: <input type = "text" name = "LabelFr"> <br/>
                    URL: <input type = "text" name = "URL"> <br/>
                    TwitterUserNames: <input type = "text" name = "TwitterUserName" size = "50">  
                    <input type = "button" value = "Add" onclick = "addTextField()"/>
                    <span id="twitterusernames">&nbsp;</span>
                    <br/>
                    Minimum Count: <input type = "text" name = "MinimumCount"> <br/>
                    Refresh Count: <input type = "text" name = "RefreshCount"> <br/>
                    EmptyMessage English: <input type = "text" name = "EmptyMessageEnglish"> <br/>
                    EmptyMessage French: <input type = "text" name = "EmptyMessageFrench"> <br/>
                    Widget: <input type = "text" name = "Widget"> <br/>
                    Email Share Text: <input type = "text" name = "EmailShareText"> <br/>
                </td> </tr>
            </table>

            <input type="submit" value="Submit">
        </form>
    </body>


</html>

and the PHP code:

<?php   
    include 'database.php';

    $Twitter = array(
        'FeatureId' => $_POST["FeatureId"],
        'Image' => $_POST["Image"],
        'LabelEn' => $_POST["LabelEn"],
        'LabelFr' => $_POST["LabelFr"],
        'URL' => $_POST["URL"],
        'TwitterUserName' => $_POST["TwitterUserName"],
        'MinimumCount' => $_POST["MinimumCount"],
        'RefreshCount' => $_POST["RefreshCount"],
        'EmptyMessageEnglish' => $_POST["EmptyMessageEnglish"],
        'Widget' => $_POST["Widget"],
        'EmailShareText' => $_POST["EmailShareText"]
        );

    $crud = new database();
    $insert = $crud -> insert($Twitter);

    if ($insert) {
        echo "Success";
    }
    else {
        echo "Values were not inserted into the database";
    }

?>

I am adding text fields to the form dynamically, but now I need to be able to store these values into a mysql database. I am able to do this if there are no dynamically created fields. Here is the code -

<!DOCTYPE HTML>
<html>
    <head>  
        <title> Company Value form </title>
        <script language = "javascript">
            function addTextField(){
                var element = document.createElement("input");
                element.setAttribute("name", "i");
                element.setAttribute("value", "sample value");
                element.setAttribute("size", 30);

                var twitter = document.getElementById("twitterusernames");
                twitter.appendChild(element);

            }

        </script>
    </head>

    <body>
        <h1> Enter the values </h1>
        <form method = "post" name = "config_form" action = "message.php">
            <table border = "1px" >
                <tr> <td>
                    <b> Twitter </b> <br/> <br/>
                    FeatureId: <input type = "text" name = "FeatureId"> <br/>
                    Image: <input type = "text" name = "Image"> <br/>
                    LabelEn: <input type = "text" name = "LabelEn"> <br/>
                    LabelFr: <input type = "text" name = "LabelFr"> <br/>
                    URL: <input type = "text" name = "URL"> <br/>
                    TwitterUserNames: <input type = "text" name = "TwitterUserName" size = "50">  
                    <input type = "button" value = "Add" onclick = "addTextField()"/>
                    <span id="twitterusernames">&nbsp;</span>
                    <br/>
                    Minimum Count: <input type = "text" name = "MinimumCount"> <br/>
                    Refresh Count: <input type = "text" name = "RefreshCount"> <br/>
                    EmptyMessage English: <input type = "text" name = "EmptyMessageEnglish"> <br/>
                    EmptyMessage French: <input type = "text" name = "EmptyMessageFrench"> <br/>
                    Widget: <input type = "text" name = "Widget"> <br/>
                    Email Share Text: <input type = "text" name = "EmailShareText"> <br/>
                </td> </tr>
            </table>

            <input type="submit" value="Submit">
        </form>
    </body>


</html>

and the PHP code:

<?php   
    include 'database.php';

    $Twitter = array(
        'FeatureId' => $_POST["FeatureId"],
        'Image' => $_POST["Image"],
        'LabelEn' => $_POST["LabelEn"],
        'LabelFr' => $_POST["LabelFr"],
        'URL' => $_POST["URL"],
        'TwitterUserName' => $_POST["TwitterUserName"],
        'MinimumCount' => $_POST["MinimumCount"],
        'RefreshCount' => $_POST["RefreshCount"],
        'EmptyMessageEnglish' => $_POST["EmptyMessageEnglish"],
        'Widget' => $_POST["Widget"],
        'EmailShareText' => $_POST["EmailShareText"]
        );

    $crud = new database();
    $insert = $crud -> insert($Twitter);

    if ($insert) {
        echo "Success";
    }
    else {
        echo "Values were not inserted into the database";
    }

?>
Share Improve this question asked May 15, 2013 at 19:00 Ashish AgarwalAshish Agarwal 14.9k31 gold badges88 silver badges126 bronze badges 7
  • Where are you actually referring to your dynamic fields in your PHP code? And you should add the type to your new fields. – CM Kanode Commented May 15, 2013 at 19:06
  • right now the dynamic fields are not there in the PHP code. That is the question, how do I go about adding those ? – Ashish Agarwal Commented May 15, 2013 at 19:07
  • refer to them by the name (i) that you used. – CM Kanode Commented May 15, 2013 at 19:09
  • You haven't really fully described the use case. How do these dynamically added fields map to fields in the database? Are there an unpredictable number of dynamic fields? Do the dynamic field represent more rows to be inserted into the DB or simply more field data on the row to be inserted? – Mike Brant Commented May 15, 2013 at 19:11
  • @CMKanode - Hmm, when I add the field and then look at the page source, I do not see those fields. So will I still be able to access those from PHP ? – Ashish Agarwal Commented May 15, 2013 at 19:12
 |  Show 2 more ments

4 Answers 4

Reset to default 3

add this element.setAttribute("name", "i[]");

Then in your php handler

        $Twitter = array(
        'FeatureId' => $_POST["FeatureId"],
        'Image' => $_POST["Image"],
        'LabelEn' => $_POST["LabelEn"],
        'LabelFr' => $_POST["LabelFr"],
        'URL' => $_POST["URL"],
        'TwitterUserName' => $_POST["TwitterUserName"],
        'MinimumCount' => $_POST["MinimumCount"],
        'RefreshCount' => $_POST["RefreshCount"],
        'EmptyMessageEnglish' => $_POST["EmptyMessageEnglish"],
        'Widget' => $_POST["Widget"],
        'EmailShareText' => $_POST["EmailShareText"],
        'extraFields' => serialize( $_POST["i"] ) // Extra fields
        );

        $crud = new database();
        $insert = $crud -> insert($Twitter);

        if ($insert) {
        echo "Success";
        }
        else {
        echo "Values were not inserted into the database";
        }

        ?>

to display the data. let's assume that you already have the $extraFields

<?php
$extraFields = unserialize( $extraFields );

 foreach($extraFields as $extra ):
?>
<input type="text" name="i[]" value="<?php echo $extra; ?> ">
<?php
endforeach;
?>

Give the dynamic elements names ending in []:

element.setAttribute("name", "i[]");

Then PHP will fill $_POST['i'] with an array of all the values.

According to your script I got idea like you are adding text box after clicking button. So when you are adding multiple textbox you need to make your textbox field name as a array i.e

<input type="text" name="i[]" value="sample data" />
<input type="text" name="i[]" value="sample data" />
<input type="text" name="i[]" value="sample data" />

Modify your addTextField() function

function addTextField(){
            var element = document.createElement("input");
            element.setAttribute("name", "i[]");
            element.setAttribute("value", "sample value");
            element.setAttribute("size", 30);

            var twitter = document.getElementById("twitterusernames");
            twitter.appendChild(element);

        }

And in message.php file you can get value through $_POST[i] in array format.

If added fields contain only secondary data, I'd just add another column with text type and just dump there JSON-encoded values of these fields in one chunk.

发布评论

评论列表(0)

  1. 暂无评论