简体   繁体   English

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

[英]How to dynamically add html elements using javascript and also keep their record in php

I have a input box where user specify the number of new DIV elements to be added dynamically,this request is than send to php via ajax where it prepares a html DIV with some inner input tags with each DIV having unique id attribute generated in incremental way using the number provided by user and sends back to JS,now JS appends this new html in existing form . 我有一个输入框,用户可以在其中指定要动态添加的新DIV元素的数量,而不是通过ajax发送到php,该请求将通过一个内部input标签准备一个HTML DIV ,每个内部DIV具有以增量方式生成的唯一id属性使用用户提供的号码并发送回JS,现在JS会以现有form将这个新的html追加。
I have also provided a remove button with every new DIV by which user can remove any dynamically added DIV . 我还为每个新的DIV提供了一个删除按钮,用户可以通过该按钮删除任何动态添加的DIV
User can keep on adding and deleting elements any no. 用户可以继续添加和删除任何元素。 of times so i dont want to use database for recoding how many elements added or deleted. 的时间,所以我不想使用数据库来重新编码添加或删除了多少个元素。
Now i need to some solution where i can create and allocate unique ids to div and also keep there record some where so that when form is submitted i can loop through those record and get user submitted data from those DIVs . 现在,我需要一些解决方案,可以在其中创建并分配唯一的idsdiv ,还可以在其中记录一些位置,以便在提交表单时可以遍历这些记录并从这些DIVs获取用户提交的数据。

1st HTML CODE: 第一个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>

2nd JS CODE 第二个JS代码

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);  } }); }

3rd PHP CODE to generate DIV 第三个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

4th JS CODE to remove div 第四个JS代码删除div

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

Check the solution here: DEMO 在此处检查解决方案: DEMO

HTML: you need get from the user the number of requested divs and put them inside a container and remember the list of divs inside the form. HTML:您需要从用户那里获取所请求的div数量,并将其放入容器中,并记住表单内的div列表。 Thus, you need an input field, a button, a container and a hidden field. 因此,您需要一个输入字段,一个按钮,一个容器和一个隐藏字段。

<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: You need to create the divs locally (function 1), then keep track of their ids (function 2). jQuery:您需要在本地创建div(功能1),然后跟踪其ID(功能2)。 You also need two global variables: one that increments the divs' ids (a counter), and one that stores all the available ids (an array). 您还需要两个全局变量:一个用于增加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();
        });
    }

}

Create action for the button that generates the divs based on user input: 为根据用户输入生成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("");
});

Thus, you can update the divs as many times you want without Ajax/PHP. 因此,您可以在不使用Ajax / PHP的情况下多次更新div。 You also get unique ids for the new divs. 您还将获得新div的唯一ID。 At the end, you have the div list inside the hidden input field, which is passed in the form. 最后,您将在隐藏的输入字段中包含div列表,该列表以表格形式传递。

Ps. PS。 You could also just process the form locally, then just send the final product to PHP by Ajax. 您也可以只在本地处理表单,然后将最终产品发送给Ajax的PHP。

OLD ANSWER: 旧答案:

You could store all the ids in an array. 您可以将所有ID存储在一个数组中。 Then update the array whenever a div is removed or added. 然后在删除或添加div时更新数组。 And when you send the form, you can simply pass the array too, so that the server can read the ids from the array, then check the inputs. 发送表单时,您也可以简单地传递数组,以便服务器可以从数组中读取ID,然后检查输入。 (you can send the array inside the Ajax request, or by putting it in a hidden input inside the form) (您可以在Ajax请求中发送数组,也可以将其放在表单中的隐藏输入中)

(I would also ask if it wouldn't be easier to create de divs locally, without ajax and php. It seems that there are a lot of back-and-forward requests.) (我还会问,如果没有ajax和php,在本地创建de divs会不会更容易。似乎有很多往返请求。)

Ps. PS。 What happens if the client asks for more divs, repeatedly? 如果客户反复要求增加div会怎样? Will there be unique ids in the form? 表格中会有唯一的ID吗? Because it seems that the PHP file will always generate ids starting from 1 to hotel no. 因为似乎PHP文件将始终生成从1到酒店编号的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM