1

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.
I have also provided a remove button with every new DIV by which user can remove any dynamically added 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.

1st HTML CODE:

<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

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

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

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

1 Answer 1

1

Check the solution here: 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. 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). You also need two global variables: one that increments the divs' ids (a counter), and one that stores all the available ids (an array).

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:

$("#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. You also get unique ids for the new divs. At the end, you have the div list inside the hidden input field, which is passed in the form.

Ps. You could also just process the form locally, then just send the final product to PHP by Ajax.

OLD ANSWER:

You could store all the ids in an array. Then update the array whenever a div is removed or added. 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. (you can send the array inside the Ajax request, or by putting it in a hidden input inside the form)

(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.)

Ps. What happens if the client asks for more divs, repeatedly? Will there be unique ids in the form? Because it seems that the PHP file will always generate ids starting from 1 to hotel no.

Sign up to request clarification or add additional context in comments.

3 Comments

As you mentioned problem regarding id starting from 1,it was also a issue which i needed to solve,that's why i wanted some solution where i can start from previous number and continue ahead. Also how would i store array in hidden input field ??
You definitely need to generate and store the ids locally. You could put at the bottom of the form a hidden input (<input type="hidden" name="ids" value="" />) that you could update by js whenever a div is added or removed. Sorry, only tomorrow i could show you how to do it. But you should try it out yourself.
I changed the answer. Check the solution in the demo. It should do the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.