【问题标题】:JavaScript add remove fields in dynamically generated formsJavaScript 在动态生成的表单中添加删除字段
【发布时间】:2014-03-26 12:28:44
【问题描述】:

一个关于如何使用 JavaScript 在动态生成的表单中添加删除字段的示例。

【问题讨论】:

    标签: javascript forms form-fields


    【解决方案1】:

        <h3>javascript add remove fields in dynamically generated forms</h3>
    <br>
    modification of http://www.quirksmode.org/dom/domform.html
    <br>
    <br><br>
    <?
    $action_url = {form action here};
    ?>
    
    
    <script type="text/javascript">
    var i = 1;
    function addCost(cost_no){
    
    
            cn = cost_no;
    
            //max nubmer of fields, for all cases together
            if (i <= 300){
                    i++;
    
             ident =  'cost['+cn+']['+i+']';   
    
    
            var div = document.createElement('div');
                    //div.style.width = "300px";
                    //div.style.height = "50px";
                    //div.style.color = "white";
                    div.setAttribute('class', 'myclass');
    
                div.innerHTML = '<input type="text" \n\
                                        name="'+ident+'"  \n\
                                        id="'+ident+'" \n\
                                 >  \n\
                                 <input type="button"     \n\
                                        value="-"         \n\
                                        onclick="removeKid('+cn+', this)"\n\
                                 >';
                document.getElementById('kids'+cn+'').appendChild(div);
            }
    }
    
    function removeKid(cost_no, div) {
    
        //alert(test);
        cn = cost_no;
    
        document.getElementById('kids'+cn+'').removeChild( div.parentNode );
            i--;
    }
    </script>
    
    <form action="<?= $action_url;?>" method="post" >
    
    <? 
    for ($cost_id=0; $cost_id<=10; $cost_id++)
      {
      echo "The form id is : $cost_id <br>";
    
    ?>   
    
        <div id="kids<?= $cost_id; ?>">
           <input type="button" 
                  id="add_cost<?= $cost_id; ?>" 
                  onClick="addCost(<?= $cost_id; ?>)" 
                  value="Add field:<?= $cost_id; ?>" 
            />
        </div>
        <br>
     <?
      }
     ?>
    
    
    
    
    <br>
    <input type="submit" name="submit" value="submit" />(limit 300)
    </form>
    

    【讨论】:

      猜你喜欢
      • 2019-04-19
      • 2016-10-20
      • 2011-05-16
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      相关资源
      最近更新 更多