douliu7929 2014-01-26 18:43
浏览 65
已采纳

PHP无法识别使用JavaScript动态添加的字段

I have a MySQL database of orders that each have various activities associated with them. My PHP/HTML page pulls down the activities when you click an order and allows the user to change attributes of the activities with a form. On submit another PHP file loops through activities in the table and runs an update query on the database. Works great!

I have recently added a JavaScript function that will add activities to the list (appendChild, createElement...). I then added to my PHP file an INSERT query for the new activities.

The problem is that when I run the update PHP file it is not looping through the newly added records that were added with JavaScript. I checked it by using <?php print $size = count($_POST['FcastID']) ?> and the value doesn't change when records have been added.

The records look fine when added to the table and the id and name convention match the other records. It seems like the page needs to be refreshed before the PHP file runs.

PHP file with dynamically created html form

<div id="submit"><form method="post" action="Up_Forecast.php"><input type="submit" value="Submit"></div>
....
<table id="fcast">
<?
$i=0;
while($row = mysqli_fetch_array($res_fcast))
{
echo "<tr id='fcastRow[$i]'>";
echo "<td class='medium'><input type='text' id='qtyJan[$i]' name='qtyJan[$i]' value='".$row[Jan]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyFeb[$i]' name='qtyFeb[$i]' value='".$row[Feb]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyMar[$i]' name='qtyMar[$i]' value='".$row[Mar]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyApr[$i]' name='qtyApr[$i]' value='".$row[Apr]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyMay[$i]' name='qtyMay[$i]' value='".$row[May]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyJun[$i]' name='qtyJun[$i]' value='".$row[Jun]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyJul[$i]' name='qtyJul[$i]' value='".$row[Jul]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyAug[$i]' name='qtyAug[$i]' value='".$row[Aug]."'/></td>";
echo "<td class='medium'><input type='text' id='qtySep[$i]' name='qtySep[$i]' value='".$row[Sep]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyOct[$i]' name='qtyOct[$i]' value='".$row[Oct]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyNov[$i]' name='qtyNov[$i]' value='".$row[Nov]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyDec[$i]' name='qtyDec[$i]' value='".$row[Dec]."'/></td>";
echo "<td class='medium'><input type='text' id='Totalqty[$i]' name='Totalqty[$i]' value='".$row[Total]."' disabled/></td>";
echo "</tr>";
++$i;
}
?>
<tr><td class="blank"></td><td class="mini"><input type="button" onclick="addRowYear(this)" value="Add"/></td></tr>
</table>
</form>
</div>

Javascript function to add row

function addRowYear(lastRow){
    var rowNo = lastRow.parentNode.parentNode.rowIndex;
    var newRow = document.getElementById("fcast").insertRow(rowNo);

    newRow.setAttribute("id","fcastRow["+rowNo+"]");

    var cell0 = newRow.insertCell(0);
    cell0.setAttribute("class","mini");
var input0 = document.createElement("input");
    input0.setAttribute("type","text");
    input0.setAttribute("name","FcastID["+rowNo+"]");
    input0.setAttribute("value","new");
    cell0.appendChild(input0);

var cell1 = newRow.insertCell(1);
    cell1.setAttribute("class","mini");
var input1 = document.createElement("input");
    input1.setAttribute("type","text");
    input1.setAttribute("name","Fcast_ActID["+rowNo+"]");
    input1.setAttribute("id","Fcast_ActID["+rowNo+"]");
    cell1.appendChild(input1);
var curAct = document.getElementById("selAct").innerHTML;
    document.getElementById("Fcast_ActID["+rowNo+"]").value = curAct;

var cell2 = newRow.insertCell(2);
    cell2.setAttribute("class","mini");
var input2 = document.createElement("input");
    input2.setAttribute("type","text");
    input2.setAttribute("name","Year["+rowNo+"]");
    cell2.appendChild(input2);

var month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
for (var i = 0; i < month.length; i++) {
//alert(month[i]);
    x=3;
var cell = newRow.insertCell(x);
    cell.setAttribute("class","medium");
var input = document.createElement("input");
    input.setAttribute("type","text");
    input.setAttribute("class","numbers");
    input.setAttribute("name","qty"+month[i]+"["+rowNo+"]");
    input.setAttribute("id","qty"+month[i]+"["+rowNo+"]");
    input.setAttribute("onkeyup","findTotal()");
    cell.appendChild(input);
    x=x+1;
    }

var cell15 = newRow.insertCell(15);
    cell15.setAttribute("class","medium");
var input15 = document.createElement("input");
    input15.setAttribute("type","text");
    input15.setAttribute("class","numbers");
    input15.setAttribute("name","Totalqty["+rowNo+"]");
    input15.setAttribute("id","Totalqty["+rowNo+"]");
    cell15.appendChild(input15);

PHP Update - Called on Submit of form

$size = count($_POST['FcastID']);
$i = 0
while ($i < $size) {
    $FcastID = $_POST['FcastID'][$i];
    $ActID = $_POST['Fcast_ActID'][$i];
    $Year = $_POST['Year'][$i];
    $Jan = $_POST['qtyJan'][$i];
    $Feb = $_POST['qtyFeb'][$i];
    $Mar = $_POST['qtyMar'][$i];
    $Apr = $_POST['qtyApr'][$i];
    $May = $_POST['qtyMay'][$i];
    $Jun = $_POST['qtyJun'][$i];
    $Jul = $_POST['qtyJul'][$i];
    $Aug = $_POST['qtyAug'][$i];
    $Sep = $_POST['qtySep'][$i];
    $Oct = $_POST['qtyOct'][$i];
    $Nov = $_POST['qtyNov'][$i];
    $Dec = $_POST['qtyDec'][$i];
    $Total = $_POST['Totalqty'][$i];
    $update = "UPDATE FCAST SET
    Year='$Year',
    Jan=replace('$Jan',',',''),
    Feb=replace('$Feb',',',''),
    Mar=replace('$Mar',',',''),
    Apr=replace('$Apr',',',''),
    May=replace('$May',',',''),
    Jun=replace('$Jun',',',''),
    Jul=replace('$Jul',',',''),
    Aug=replace('$Aug',',',''),
    Sep=replace('$Sep',',',''),
    Oct=replace('$Oct',',',''),
    Nov=replace('$Nov',',',''),
    `Dec`=replace('$Dec',',',''),
    Total=replace('$Total',',','')
    WHERE
    FcastID='$FcastID'";
    mysqli_query($link, $update);
  • 写回答

1条回答 默认 最新

  • dongtuo7364 2014-01-26 18:50
    关注

    Without seeing your code, it is difficult to say. Something I have used in the past that works well is the following:

    PHP:

    foreach($_POST as $key => $value) {
        //... $key is name of field, $value is the value
    }
    

    This goes through each individual field in the submitted form and reads the value in each. I've used this exact script for dynamically-created forms, and it works great. You have to be careful, though, if you use the same name for different fields, the values will be stored as arrays.

    EDIT

    HTML:

    <form method="post" action="index.php">
    <div>
      <div>
        <p>
        <label class="reg_label" for="field_name">Item:</label>
        <input class="text_area" name="field_name[]" type="text" id="testing" tabindex="98" style="width: 150px;"/>
        </p>
      </div>
    </div>
    <input type="button" id="btnAdd" value="Add" class="someClass1"/>
    <input type="button" id="btnDel" value="Remove" class="someClass2" disabled/><br><br>
    <input type="submit" id="submit" name="submit" value="Submit">
    </form>
    

    JavaScript:

    var j = 0;
    $(document).ready(function () {
        $('.someClass1').click(function (e) {
    
            var num = $(this).prev().children().length; 
            var newNum = new Number(num + 1); 
    
            var newElem = $(this).prev().children(':last').clone().attr('id', 'input' + newNum);
    
            if(newElem.children().children().last().hasClass('otherOption')){
                newElem.children().children().last().remove();
            }
    
            newElem.children().children().each(function(){
                var curName = $(this).attr('name');
                var newName = '';
                $(this).attr('id', 'name' + num + '_' + j);
                j++;
            });
    
            newElem.children().children().each(function(){
                $(this).removeAttr('value');
            });
    
            $(this).prev().children(':last').after(newElem);
    
            $(this).next().removeAttr('disabled');
        });
    
        $('.someClass2').click(function (e) {
            var num = $(this).prev().prev().children().length; 
    
            $(this).prev().prev().children(':last').remove(); 
            if (num - 1 == 1) $(this).attr('disabled', 'disabled');
        }); 
    });
    

    It isn't all that important to know how the JavaScript code works. All you need to know is that clicking on the "Add" button will duplicate the field and clicking on "Remove" will remove the most recently added field. Try it out at the link provided.

    PHP:

    This is where the magic happens…

    <?php 
    if(isset($_POST['submit'])){
        foreach($_POST as $name => $item){
            if($name != 'submit'){
                for($m=0; $m < sizeof($item); $m++){
                    echo ($name.' '.$item[$m].'<br>');
                }
            }
        }
    }
    ?>
    

    Looks easy enough, right?

    This PHP code is within the same file as the form, so first we check to see if the form has been submitted by checking for the name of the submit button if(isset($_POST['submit'])){…}.

    If the form has been submitted, go through each submitted item foreach($_POST as $name => $item){…}.

    The submit button counts as one of the fields submitted, but we aren't interested in storing that value, so check to make sure the value you are reading in is not from the submit button if($name != 'submit'){…}.

    Finally, all the fields within this form have the same name field_name[]. The square brackets are used for multiple items that share the same name. They are then stored in an array. Read through each item within that array for the length of the array for($m=0; $m < sizeof($item); $m++){…} and then do what you'd like with each value. In this case, I've just printed them to the screen echo ($name.' '.$item[$m].'<br>');

    Below are a couple screen-shots of the page…

    Before submitting the form:

    Before

    After submitting the form:

    After

    You can go to the page and view the code (right click -> View Source), but the PHP will not show up in the source. I assure you that all the PHP used for this is shown above - just the few lines.

    If each item has a completely unique name (which you can achieve via JavaScript when adding fields), then you will not need to loop through the array of values (i.e. will not need for($m=0; $m < sizeof($item); $m++){…} block). Instead, you'll likely read the value using simply $item. If you name your fields with the square brackets (i.e. field_name[]), but only have one of that field, then reading a singular value may require $item or $item[0]. In that case you'll just have to test it and see. Some field types behave differently than others (i.e. input, text area, radio buttons, etc).

    The Whole Thing

    Here is the entire code for index.php - you can just copy and paste it and run it on your own server. Just make sure to change the name of the file in the action attribute <form> tag…

    <?php 
    if(isset($_POST['submit'])){
        foreach($_POST as $name => $item){
            if($name != 'submit'){
                for($m=0; $m < sizeof($item); $m++){
                    echo ($name.' '.$item[$m].'<br>');
                }
            }
        }
    }
    ?>
    
    <html>
    <head>
    <script type="text/javascript" src="../scripts/jquery-1.8.2.min.js"></script>
    </head>
    <body>
    
    <form method="post" action="index.php">
    <div>
      <div>
        <p>
        <label class="reg_label" for="field_name">Item:</label>
        <input class="text_area" name="field_name[]" type="text" id="testing" tabindex="98" style="width: 150px;"/>
        </p>
      </div>
    </div>
    <input type="button" id="btnAdd" value="Add" class="someClass1"/>
    <input type="button" id="btnDel" value="Remove" class="someClass2" disabled/><br><br>
    <input type="submit" id="submit" name="submit" value="Submit">
    </form>
    
    </body>
    
    <script>
    var j = 0;
    $(document).ready(function () {
        $('.someClass1').click(function (e) {
    
            var num = $(this).prev().children().length; 
            var newNum = new Number(num + 1); 
    
            var newElem = $(this).prev().children(':last').clone().attr('id', 'input' + newNum);
    
            if(newElem.children().children().last().hasClass('otherOption')){
                newElem.children().children().last().remove();
            }
    
            newElem.children().children().each(function(){
                var curName = $(this).attr('name');
                var newName = '';
                $(this).attr('id', 'name' + num + '_' + j);
                j++;
            });
    
            newElem.children().children().each(function(){
                $(this).removeAttr('value');
            });
    
            $(this).prev().children(':last').after(newElem);
    
            $(this).next().removeAttr('disabled');
        });
    
        $('.someClass2').click(function (e) {
            var num = $(this).prev().prev().children().length; 
    
            $(this).prev().prev().children(':last').remove(); 
            if (num - 1 == 1) $(this).attr('disabled', 'disabled');
        }); 
    });
    </script>
    
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站