如何使用javascript动态添加html元素,并将其记录保存在php中

时间:2015-07-26 10:31:14

标签: javascript php jquery html dynamic

我有一个输入框,其中用户指定要动态添加的新DIV元素的数量,此请求不是通过ajax发送到php,在那里它准备带有内部{DIV的html input 1}}标签,每个DIV具有唯一id属性,使用用户提供的数字以增量方式生成并发送回JS,现在JS将此新html附加到现有form。<登记/> 我还为每个新DIV提供了一个删除按钮,用户可以删除任何动态添加的DIV
用户可以继续添加和删除元素。因此我不想使用数据库来重新编码添加或删除的元素数量 现在我需要一些解决方案,我可以创建并分配唯一的idsdiv,并在那里记录一些地方,以便在提交表单时,我可以遍历这些记录并从那些记录中获取用户提交的数据DIVs

第一个HTML代码:

<tr><td>No. Of Hotel</td><td><input type="text" id="noofhotel" name="noofhotel">
<input class="btn green" type="button" value="Submit" onclick="get_multiple_hotel_div()"></td></tr>

第二个JS CODE

function get_multiple_hotel_div(){
var hotel_no = $("#noofhotel").val();

input_form_data = {
    hotel_no : hotel_no
}

$.ajax({
        type : "POST", //TODO: Must be changed to POST
        data : input_form_data,
        url: 'index.php?/process_transcation/get_multiple_hotel_div',
        beforeSend : function(){
            $('#loading_div').html("<img src='public/images/loading_red.gif' style='margin-left:50%; margin-top:5%;'>");
        },
        success : function(data_response){
            $('#loading_div').empty();
            data_response = $.parseJSON(data_response);
            $('#multi_hotel_table').append(data_response.div_form);  } }); }

第三个PHP代码生成DIV

function get_multiple_hotel_div($hotel_no){

    for($i=1;$i<=$hotel_no;$i++){
    $hotelinput_form.="<div class='subtask_input_form_div multi_hotel_div' id='hoteldiv_".$i."'><p class='basic_eq_div_p'>Hotel Entry&nbsp&nbsp&nbsp&nbsp&nbsp<input type='button' id='remove' name='remove' value='Remove' class='btn green' onclick='remove_div(\"hoteldiv_$i\")'></p>
                        <table>
                        <tbody>
                        <tr>
                        <td style='display:none;'><input type='hidden' id='hotelid_".$i."' name='mhotelno[]'></td>
                        </tr>                   
                        <tr>
                        <td class='headtd'>Hotel Name</td>
                        <td class='headtd'><input type='text' id='mhotelname_".$i."' class='mhotel' name='mhotelname_".$i."' style='width:90% !important;' onkeyup='search_dropdown_data(this.value,this.id,\"hotel_table_$i\",\"mhotelid_$i\",\"$supplier_master_table\")'><div class='dropdown_div'><table id='hotel_table_".$i."' class='dropdown_table'></table></div></td>
                        <input type='hidden' id='mhotelid_".$i."' name='mhotelid_".$i."' class='mhotel'>
                        <td class='headtd'>Destination </td>
                        <td class='headtd'><input type='text' id='mdestination_".$i."' class='mdestination' name='mdestination_".$i."' style='width:90% !important;' onkeyup='search_dropdown_data(this.value,this.id,\"rt_to_table_$i\",\"mdestinationid_$i\",\"$destination_master_table\")'><div class='dropdown_div'><table id='rt_to_table_".$i."' class='dropdown_table'></table></div></td>
                        <input type='hidden' id='mdestinationid_".$i."' name='mdestinationid_".$i."' class='mdestination'>
                        </tr></tbody>
                        </table>
                        </div>";
    }// End of for loop     

    $response_array = array("div_form"=>$hotelinput_form);  
    return json_encode($response_array);                                    

}//end of function

第四个JS CODE删除div

function remove_div(div_id){
$("#"+div_id).remove();}

1 个答案:

答案 0 :(得分:1)

在此处查看解决方案:DEMO

HTML:您需要从用户那里获取所请求的div的数量并将它们放在容器中并记住表单中的div列表。因此,您需要输入字段,按钮,容器和隐藏字段。

<input name="nr_divs" type="text" maxlength="2" />
<button id="b-new-div">+</button>
<form>
<div id="container"></div>
<input type="hidden" id="div_id_list" name="div_id_list" value="" />
</form>

jQuery:你需要在本地创建div(函数1),然后跟踪它们的id(函数2)。您还需要两个全局变量:一个增加div的ID(一个计数器),另一个存储所有可用的ID(一个数组)。

var nr_div=0; // the counter
var div_list=[]; // the storage

function updateDivList(id, action) {

    /* 
    id = the div id
    action= add or remove a div from the list
    */

    if (action>0) { // add new div in the list
        div_list.push(id);
    } else { // remove a div from the list
        var temp=[];
        for (var i=0; i<div_list.length; i++) {
            if (div_list[i]!=id) {
                temp.push(div_list[i]);
            }
        }
        div_list=temp;
    }
    // Put the div list in the hidden field, inside the form
    $("#div_id_list").val(div_list.join(","));
}

function newDiv(container, div_query) {

    /*
    container = where does the new div go?
    div_query = how many divs?
    */

    var html="<div div-id=\""+nr_div+"\" >";
    html+="<button class=\"b-remove\" type=\"button\">remove</button>";
    html+="/* Your HTML code goes here*/";
    html+="</div>";

    $(container).append(html); // the div appears in the container

    updateDivList(nr_div,1); // add the new div in the list

    nr_div++; // increase the counter

    if (div_query-1 > 0) { // if more divs are needed, recall function
        newDiv(container, div_query-1);
    } else { // add remove div action to the inside button
        $(".b-remove").click(function(){ 
            updateDivList($(this).parent().attr("div-id"),-1);
            $(this).parent().remove();
        });
    }

}

根据用户输入为生成div的按钮创建操作:

$("#b-new-div").click(function(){
            var nr=$("input[name='nr_divs']").val();
            if (nr.length>0 && !isNaN(nr)) {
                newDiv("#container",nr);
            }
            $("input[name='nr_divs']").val("");
});

因此,您可以在没有Ajax / PHP的情况下多次更新div。您还可以获得新div的唯一ID。最后,你在隐藏输入字段中有div列表,它在表单中传递。

聚苯乙烯。您也可以在本地处理表单,然后通过Ajax将最终产品发送给PHP。

老答案:

您可以将所有ID存储在数组中。然后每当删除或添加div时更新数组。当您发送表单时,您也可以简单地传递数组,以便服务器可以从数组中读取ID,然后检查输入。 (您可以在Ajax请求中发送数组,或者将其放在表单内的隐藏输入中)

(我还会问,在没有ajax和php的情况下在本地创建de div会不会更容易。似乎有很多后退请求。)

聚苯乙烯。如果客户端反复要求更多div,会发生什么?表格中会有独特的ID吗?因为似乎PHP文件总是会生成从1开始到酒店编号的ID