如何从html表单数组元素创建javascript数组

how to create javascript array from html form array elements

本文关键字:创建 javascript 数组 数组元素 表单 html      更新时间:2023-09-26

这是我的html代码

  <table width="62%" height="70" border="1" cellpadding="0" cellspacing="0" id="edit">              
    <?php if(count($voucher_info) > 0 ){ ?>
        <tr class="bgcolor_02">
            <td width="27%" align="center"   class="admin" >S.no</td>
            <td width="37%" align="center"   class="admin" >Voucher Type</td>
            <td width="47%" align="center"   class="admin" >Voucher Mode</td>

        </tr>
        <?php 
        $rownum = 1;    
        foreach($voucher_info as $eachrecord){
            $zibracolor = ($rownum%2==0)?"even":"odd";
            ?>
            <tr align="center"  class="narmal">
                <td height="25"><?php echo $eachrecord->voucher_id ; ?><input type="hidden" name="voucher_id[]" value="<?php echo $eachrecord->voucher_id; ?>" /></td>
                <td><input name="vouchertype[]" type="text" value="<?php echo $eachrecord->voucher_type; ?>"  id="vouchertype"/></td>   
                <td><select name="mode[]" >
                        <option value="paidin" <?php if($eachrecord->voucher_mode=='paidin'){ ?> selected="selected" <?php } ?>>Paid In</option>
                        <option value="paidout" <?php if($eachrecord->voucher_mode=='paidout'){ ?> selected="selected" <?php } ?>>Paid Out</option>
                    </select></td>                  
            </tr>
            <?php
            }
            }                   
    else{
        echo "<tr class='bgcolor_02'>";
        echo "<td align='center'><strong>No records found</strong></td>";
        echo "</tr>";
    } 
    ?>
</table>
<input id="update" type="submit" name="submit" value="Edit"/>

我只想知道如何在javascript中访问vouchertype和mode,并使用ajax将它们传递给控制器。我想将更新后的值保存到数据库中。请任何人有任何想法,然后告诉我。

首先,HTML是无效的,因为文档中的每个元素id都必须是唯一的。如果不是,则不能使用该id来选择元素。

在这段代码中,删除id或为每一行生成一个唯一的id。

 <input name="vouchertype[]" type="text" value="<?php echo $eachrecord->voucher_type; ?>"  id="vouchertype"/>

<input name="vouchertype[]" type="text" value="<?php echo $eachrecord->voucher_type; ?>"/>

按名称选择字段,然后在集合上迭代以获得值。

function saveValues(){
    var types = $('input[name="vouchertype[]"]'),
    modes = $('select[name="mode[]"]'),
    typeValues = [], modeValues = [];
    types.each(function(el){
        typeValues.push(el.val())})
    modes.each(function(el){
        modeValues.push(el.val() ? el.val()[0] : false)})
    $.ajax(
         data: {vouchertype: typeValues, mode: modeValues},
        ...