JavaScript在动态生成的表单中添加删除字段

时间:2014-03-26 12:28:45

标签: javascript forms form-fields

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

1 个答案:

答案 0 :(得分:0)

enter image description here

POST

    <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>