简体   繁体   中英

Populate jquery form from nested array of $_POST

PHP form uses a jquery script to add fields and sub-fields based on http://jsfiddle.net/L3s3w/4/ .

$(function(){
    var nbIteration = 1;
    var detailIteration = 1;
    $("#addIteration").click(function(){
        nbIteration++;
        $("#content-contact").append('<div class="iteration"><h3>Track '+ nbIteration +'<span class="controlButtons"><input type="button" value="+" class="plus" /><input type="button" value="-" class="moins" /></span></h3><input type="text" name="Track'+ nbIteration +'" value="Track Title" /></div>');
    });
    $("#removeIteration").click(function(){
        if($(".iteration").length > 0){
            nbIteration--;
            $(".iteration").last().remove();
        }
    });
    $("#content-contact").on("click", ".plus",function(){
        var parent = $(this).closest(".iteration");
        parent.append('<input type="text" value="Track Details" name="Track_'+ nbIteration + '_' + detailIteration +'"/>');
        detailIteration++;
        var nbinput = parent.find("input[type='text']").length;
        if(nbinput == 5)
            parent.find(".plus").prop("disabled",true);
        if(nbinput > 0)
            parent.find(".moins").prop("disabled",false);
    });
    $("#content-contact").on("click",".moins", function(){ 
        var parent = $(this).closest(".iteration");
        parent.children("input").last().remove();
        var nbinput = parent.find("input[type='text']").length;
        if(nbinput < 5)
            parent.find(".plus").prop("disabled",false);
        if(nbinput == 0)
            parent.find(".moins").prop("disabled",true);
    });
});

I am using php to validate the form and re-populating the fields by simply recreating the initial jquery-rendered fields based on a nested array generated from the $_POST data.

         $num_tracks = 0;
         $num_deets = 0;
        foreach ($_POST as $detail => $specific)
        {//If it's not one of the fields above
            if (!in_array($detail, $basic_info))

                //If no underscore goes in outer array
                if (!strpos($detail, "_"))
                    {
                    if ($num_deets != 0) $num_tracks++;
                    //assign new top level key for track
                    $tracks[$num_tracks][$detail] = $specific;
                    }
            else
                {
                $tracks[$num_tracks][$detail] = $specific;
                $num_deets++;
                }

then recreating the fields in php:

        <?php //if we have tracks
        if (isset($tracks)){
            $track_no = 0;
            $detail_no = 0;
            foreach ($tracks as $track => $track_detail)
            {
            $track_no++;
            ?>
             <h3>Track <?php echo "$track_no"; ?> <span class="controlButtons"><input type="button" value="+" class="plus" /><input type="button" value="-" class="moins" /></span></h3>
             <?php foreach ($track_detail as $detail => $specific)
             {
             $detail_no++;
             ?>
             <input type="text" value="<?php echo $specific; ?>" name="<?php echo $detail; ?>"/>
             <?php } ?>
            <?php
            }
        }else{

I experimented with using php count variables in the jquery but soon realized that the jquery to add and remove fields was no longer functioning because of the iterations not being within the jquery code.

Is there a jquery variation of the final part of the php script (above) that I could use to recreate the jquery form fields, populated with $_POST data from my nested array, or is this going to require rewriting the script to use ajax and/or JSON in the form processing?

Thanks for your insights.

The answer is that yes, JavaScript would have to handle the form validation if it was going to return dynamicly generated fields populated with the $_POST data and continue to manipulate them (add and delete fields). So to send the form data to php would require a second php file and ajax to load the info on the page.

Ended up just using http://formvalidator.net/ to validate before submitting to server, then and return the submitted values only for viewing (not updating).

This is the code to parse the data from the form, separating the top level iteration fields from the secondary (or additional fields) to send to email or browser:

//Define what is not to be considered as a track detail
 $basic_info = array('Name','Email','Notes','Project_Name','Artist_Name');

 $num_tracks = 0;
foreach ($_POST as $detail => $specific)
{//If it's not one of the fields above
    if (!in_array($detail, $basic_info))
        //If no underscore it's a TRACK so goes in outer array
        if (!strpos($detail, "_"))
            {
            $num_deets = 0; // reset number of details
            $num_tracks++; // we have a new track
            //assign new top level key for track
            $tracks[$num_tracks][$detail] = $specific;
            $num_deets++; //we have one detail
            }
    else
            {
            //assign to secondary array of details
            $tracks[$num_tracks][$detail] = $specific;
            $num_deets++;//we have a new detail
            $detail = "\tDetail";
            }
            //add to the message with underscore removed
        $message .= "\n" . str_replace("_", " ", $detail).": ". $specific."\n";
    } 

Here's the javascript:

<script type="text/javascript">
$(function(){
    var nbIteration = 1;
    var detailIteration = 1;
    $("#addIteration").click(function(){
        nbIteration++;
    var detailIteration = 1;
        $("#content-contact").append('<div class="iteration"><h3>Track '+ nbIteration +'<span class="controlButtons"><input type="button" value="+" class="plus" /><input type="button" value="-" class="moins" /></span></h3><input type="text" name="Track'+ nbIteration +'" value="Track Title" /></div>');
    });
    $("#removeIteration").click(function(){
        if($(".iteration").length > 0){
            nbIteration--;
            $(".iteration").last().remove();
        }
    });
    $("#content-contact").on("click", ".plus",function(){
        var parent = $(this).closest(".iteration");
        parent.append('<input type="text" value="Track Details" name="Track_'+ nbIteration + '_' + detailIteration +'"/>');
        detailIteration++;
        var nbinput = parent.find("input[type='text']").length;
        if(nbinput == 5)
            parent.find(".plus").prop("disabled",true);
        if(nbinput > 0)
            parent.find(".moins").prop("disabled",false);
    });
    $("#content-contact").on("click",".moins", function(){ 
        var parent = $(this).closest(".iteration");
        parent.children("input").last().remove();
        var nbinput = parent.find("input[type='text']").length;
        if(nbinput < 5)
            parent.find(".plus").prop("disabled",false);
        if(nbinput == 0)
            parent.find(".moins").prop("disabled",true);
    });
});
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.1.47/jquery.form-validator.min.js"></script>


<script> $.validate({
  form : '#registration'
}); </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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