简体   繁体   中英

how to get value of dynamically added text boxes?

I have a code in jquery to add and remove the textboxes dynamically on button click. I want to post the values of dynamically created text on same page.

the code is here :

<div id="itemRows">

Item quantity: <input type="text" name="add_qty" size="4" /> 
Item name: <input  type="text" name="add_name" /> 
Item Price: <input type="text" name="add_price" /> 
Total: <input type="text" name="total" /> 
<input onclick="addRow(this.form);" type="button" value="Add row" /> 
</div>

<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'"> Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> Item Price: <input type="text" name="price[]" value="'+frm.add_price.value+'">Total: <input type="text" name="total[]" value="'+frm.total.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}

function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>

Well you already have correct names for each field, like qty[] , name[] etc. so when these values are posted to some page, each of them will appear in array. For example, you have 3 boxes with values of name and qty filled and they are sent. This is how they will appear:

[name] => Array
    (
        [0] => name1
        [1] => name2
        [2] => name3
        [3] => name4
    )
[qty] => Array
    (
        [0] => qty1
        [1] => qty2
        [2] => qty3
        [3] => qty4
    )

So, name[0] will have qty[0] too as they are in same index order. Now lets say you want to save them in database, this is how you can do it:

$data=array();
foreach($_POST['name'] as $key=>$val){  //$key is index, and $val is value posted
    $data[] = array(
         'name' =>  $_POST['name'][$key] //it will add name of that index to this array... 
        ,'qty'  =>  $_POST['qty'][$key]  //it will add qty of that index to this array...
        //and rest of yoru posted data too, like price etc etc...
    );
}

Now you have an array of information where you have all the data in organised form. If you are not sure what it is doing just print_r($data) and you will see what it has made for you.

echo "<pre>";
    print_r($data);
echo "<pre>";

I am sure, it is easy now for you to play around with this $data array.

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