简体   繁体   中英

PHP: How do I reference an element whose name I dynamically added using JQuery?

this is my second time asking for help here so I hope you don't mind if I make a mistake.

See I have a problem accessing an element (In this case, it's a < td >). I dynamically added it's name using JQuery as I 'echoed' it. I did this because the values inside the table it belongs to, are chosen by the user and is triggered by a button click.

Here's the JQuery:

$("#tblAddServices tbody").delegate("tr", "click", function(){

     firstCellServ = $("td:first", this).text();
     secondCellServ = $("td:eq(1)", this).text();
     thirdCellServ = $("td:eq(2)", this).text();
     fourthCellServ = $("td:eq(3)", this).text();
})

$('.service').on('click', function(e){

var $table = $("#tblServiceIncluded");

var newTR = $("<tr><td colspan=\"3\" name=\"servID[]\">"+firstCellServ+"</td>
                   <td colspan=\"3\">"+secondCellServ+"</td>
                   <td colspan=\"3\">"+thirdCellServ+"</td>
                   <td colspan=\"2\" class=\"sumService\">"+fourthCellServ+"</td>
               </tr>");

$table.append(newTR);

});

Now, I have a PHP script that should be getting the value(s) of the first column of the table which I named 'servID[]'. I am using an array to get its values but I always end up with an Undefined Index warning for the 'servID'.

This is the PHP script:

<?php


if(isset($_POST['btnSavePack']))
{

    $serviceArray = array();

    foreach($_POST['servID'] as $serviceKey){           
    $serviceArray[] = $serviceKey;
    }

    foreach($serviceArray as $result) {
    echo $result, '<br>';
    }
}

?>  

I hope you someone could help me figure out a way to make this work. I know I could do this with Ajax but I prefer this method since I am only a beginner. Thank you.

您可以将值放在隐藏类型的输入框中。

"<td colspan=\"3\"><input name=\"servID[]\" type=\"hidden\" value=\""+firstCellServ+"\"/>"+firstCellServ+"</td>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM