ChriChri
ChriChri

Reputation: 275

saving value from inputs which are displayed/ added via jquery

Part of a site I'm working on, involves adding <input>s using jquery, so as the user can insert further details, depending on their requirements. I am getting a bit stuck in how to save the values when these are inserted in the input boxes generated via jquery.

Here is the jsfiddle: https://jsfiddle.net/57xrg040/

<form id="multiphase" method="POST" enctype="multipart/form-data"> 
<div id="step1"> .. </div>
<div id="step2"> .. </div>
<div id="step3"> .. 
<div class="shape" id="plan4_shape">
    <span class="bakkant">
    <input class="measures" id="plan4_width" placeholder="mm" name="p4_width"/>
      <span class="times"> &times;</span> 
      <input class="measures" id="plan4_width" placeholder="mm" name="p4_length"/>
 </span>
<script id="template" type="text/template">
<span class="bakkant" id="bakkant">
<input class="measures" id="plan4_width" placeholder="mm" name="p4_width"/>
 <span class="times"> &times;</span> 
 <input class="measures" id="plan4_width" placeholder="mm" name="p4_length"/>
 <button class="close" id="close">&times;</button>
</span>
</script>
<button type="button" name="add_row" class="addrow" id="addrow4" onClick="addrow()">Add row</button>                    <textarea name="more_info" id="profiles" placeholder="Beskriv fritt, vilka kanter du vill få profilerade."></textarea>
</div>
<button  type="button" class="nasta" onClick="processStep3()">Nasta</button>
</div>
 <div id="step4"> .. </div>
<div id="step5"> .. 
<button  type="button" class="nasta" onClick="processStep3()">Nasta</button></div>
</form>

Jquery to used to add more rows

$(function() {
  var i = 0;
  $('#addrow4').click(function() {
    var $clone = $($('#template').html());
    $clone.attr('id', "bakkant" + ++i);
    $('.bakkant').prepend($clone);
  });

  $('.shape').on('click', '.close', function() {
    $(this).closest('.bakkant').remove();
  });

});

jquery used to process the step in which the inputs are found

function processStep3() {
  var hasValue = false;
  /*plan 1 */  
    plan1width = $("input[name='plan1_width']").val();
    plan1length = $("input[name='plan1_length']").val();
 /* plan 2 */
    plan2_1 = $("input[name='plan2_1']").val();
    plan2_2 = $("input[name='plan2_2']").val();
    plan2_3 = $("input[name='plan2_3']").val();
    plan2_4 = $("input[name='plan2_4']").val();
/* plan 3 */
    plan3_1 = $("input[name='plan3_1']").val();
    plan3_2 = $("input[name='plan3_2']").val();
    plan3_3 = $("input[name='plan3_3']").val();
    plan3_4 = $("input[name='plan3_4']").val();
    plan3_5 = $("input[name='plan3_5']").val();
    plan3_6 = $("input[name='plan3_5']").val();
    $('.measures').each(function (index, elem){
    if ($(elem).val()!=""){
   hasValue=true;
  }
  })
    if (hasValue) {
        _("step4").style.display = "block"; 
        $("#phase3").removeClass("phase");
        $("#phase4").removeClass("main_list");
        $("#phase3").addClass("main_list");
        $("#phase4").addClass("phase");
        $("#alert3").hide();

    } else {
        $("#alert3").show();
    }


}

At the end I would like something similar to: 1 - width 1, lenght1 2 - width2, length2 ect depening on the amount of "rows" added. The values are to then be sent via an email, so I would like to either save them as php varialbes, or in a textbox, which is then sent. This is part of a multiphase form, involving 5 steps.

This code will be processed in an email form -

if ($_POST) {
    $name = $_POST['firstlastname'];
    $guest_email = $_POST['email'];

    $empty = false;

            function IsInjected($str) {
            $injections = array('(\n+)',
                '(\r+)',
                '(\t+)',
                '(%0A+)',
                '(%0D+)',
                '(%08+)',
                '(%09+)'
            );
            $inject = join('|', $injections);
            $inject = "/$inject/i";
            if (preg_match($inject, $str)) {
                return true;
            } else {
                return false;
            }
        }

        if (IsInjected($guest_email)) {
          echo "";

          } else {
            $email_from = $name; //<== update the email address
            $email_subject = "You have a new message from $name";


            // message 
            $message = "<html><body style='font-family: Arial, Helvetica, sans-serif;'>".
            "<table border='0' cellpadding='0' cellspacing='0' 
            "</table>".
            "</table>".
            "</body></html>";

            $to = ""; //<== enter personal email here

                    // headers
            $headers = "From: $email_from \r\n";
            $headers .= "Reply-To: $guest_email \r\n";
            $headers .= "BCC: $guest_email \r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html;  charset=UTF-8 \r\n";
            //Send the email!
            mail($to, $email_subject, $message, $headers);

             echo $message;
 if(mail($to, $email_subject, $message, $headers)){ echo "Sent"; }else{ echo "Not sent";} 
                        //done. redirect to thank-you page.
 //  header('Location: back to form');
          }
}
?>

Upvotes: 1

Views: 76

Answers (2)

robrich
robrich

Reputation: 13205

$('#somebutton').click(function (e) {
    e.preventDefault();

    var data = {};
    $('#someparentdiv input').each(function () {
        var id = this.id; // or $(this).attr('id');
        var val = this.value; // or $(this).val();
        // note radio buttons and check boxes behave differently but you're not using them
        data[id] = val;
    });

    $.post('/the/page.php', JSON.stringify(data), function (r) {
        console.log('/the/page.php said ');
        console.log(r);
    });
});

Upvotes: 1

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12882

There is no need to save all the data in the textbox, you can send data directly. I would suggest you to wrap all your inputs into a <form> tag, and use jQuery.serialize() method in combination with jQuery.post().

But before doing that, I want to pay your attention that by cloning template in the way you do, all name and id attributes remain the same. You should better change them, name attribute is crucial for form serializing in that particular case.

Final code should look like:

$(function() {
  var i = 0;
  $('#addrow4').click(function() {
    var $clone = $($('#template').html());
    $clone.attr('id', "bakkant" + ++i);
    $clone.find('input[rel=\'length\']').attr('name', 'p' + i + '_length');
    $clone.find('input[rel=\'width\']').attr('name', 'p' + i + '_width');

    // change other attributes

    $('.bakkant').prepend($clone);
  });

  $('.shape').on('click', '.close', function() {
    $(this).closest('.bakkant').remove();
  });
  $('.shape').on('click', '#send', function() {
    var data = $("#myForm").serialize();
    $.post('/script_url.php', JSON.stringify(data), function (response) {
       //response here
    });
  });
});

Don't forget to wrap inputs into the form:

<form name="myForm" id="myForm">  
<span class="bakkant">
   <input class="measures" rel="width" id="plan4_width" placeholder="mm" name="p4_width"/>
   <span class="times"> &times;</span> 
   <input class="measures" rel="height" id="plan4_height" placeholder="mm" name="p4_length"/>

https://jsfiddle.net/hxzmhdwd/5/

Upvotes: 0

Related Questions