How do I get Dynamic form Value - javascript

I try to create dynamic form that will allow user to select option and populate price automatically in input field but unfortunately it only work in first field, it does not work in another added field. please help.
Here is my code
<select class="form-control item" name="madic" id="medicine" required>
<option value="" selected >Select Madicine</option>
<?php
$query2 ="SELECT * FROM pharmacy WHERE Qty != '0'";
$result2 = $con->query($query2);
if($result2->num_rows> 0){
while($optionData1=$result2->fetch_assoc()){
$mid =$optionData1['p_id'];
$madicine =$optionData1['madicine'];
$mrate =$optionData1['mrate_price'];?>
?>
<option value="<?php echo $mid ?>" data-price=<?php echo $mrate; ?>><?php echo $madicine; ?></option>
<?php }} ?>
</select>
</div>
<div class="col col-md-2">
<input type="text" name="mrate[]" value="0" class="mrate form-control " id="mrate" readonly>
</div>
<div class="col col-md-1">
<input type="text" name="Qty[]" class="form-control Qty" value="1" id="Qty" >
</div>
<div class="col col-md-1">
<input type="text" name="mdiscount[]" class="form-control mdiscount" value="0" id="mdiscount" >
</div>
<div class="col col-md-2">
<input type="text" name="pack[]" class="form-control" placeholder="eg: Tab,box .." >
</div>
<div class="col col-md-1">
<button type="button" id="add" class="btn btn-success">+</button>
</div>
JQUERY
$('select[name="madic"]').change(mediSum);
function mediSum(){
var elemente = $('select[name="madic"]').find('option:selected');
var desc1 = Number(elemente.data("price"));
var rate2 = $('.mrate').val(desc1);
}
Here I have Appended
$(document).ready(function(){
var i = i;
$('#add').click(function(){
i++;
$('#mad').append('<div id="row'+i+'"><div class="col col-md-4"><select class="form-control medicine" name="madic[]" id="medicine" required><option value="" selected >Select Madicine</option><?php
$query2 ="SELECT * FROM pharmacy WHERE Qty != '0'";
$result2 = $con->query($query2);
if($result2->num_rows> 0){
while($optionData1=$result2->fetch_assoc()){
$mid =$optionData1['p_id'];
$madicine =$optionData1['madicine'];
$mrate =$optionData1['mrate_price'];?>
?><option value="<?php echo $mid ?>" data-price=<?php echo $mrate; ?>"><?php echo $madicine; ?></option><?php }} ?>
</select></div><div class="col col-md-2"><input type="text" name="mrate[]" value="0" class="mrate form-control " id="mrate" readonly></div><div class="col col-md-1"><input type="number" name="Qty[]" class="form-control Qty" value="1" id="Qty" ></div><div class="col col-md-1"> <input type="number" name="mdiscount[]" class="form-control discount" value="0" id="mdiscount" ></div><div class="col col-md-2"><input type="text" name="pack[]" class="form-control" placeholder="eg: Tab,box .." ></div><div class="col col-md-1"><button type="button" id="'+i+'" class="btn btn-danger remove_row">-</button></div></div>');
});
$(document).on('click','.remove_row', function(){
var row_id = $(this).attr('id');
$('#row'+row_id+'').remove();
});
});
$(document).ready(function(){
var i = i;
$('#add').click(function(){
i++;
$('#mad').append('<div id="row'+i+'"><div class="col col-md-4"><select class="form-control medicine" name="madic[]" id="medicine" required><option value="" selected >Select Madicine</option><option value="1" data-price="125">Amoxline1</option><option value="2" data-price="163">Amoxline2</option><option value="3" data-price="723">Amoxline3</option>
</select></div><div class="col col-md-2"><input type="text" name="mrate[]" value="0" class="mrate form-control " id="mrate" readonly></div><div class="col col-md-1"><input type="number" name="Qty[]" class="form-control Qty" value="1" id="Qty" ></div><div class="col col-md-1"> <input type="number" name="mdiscount[]" class="form-control discount" value="0" id="mdiscount" ></div><div class="col col-md-2"><input type="text" name="pack[]" class="form-control" placeholder="eg: Tab,box .." ></div><div class="col col-md-1"><button type="button" id="'+i+'" class="btn btn-danger remove_row">-</button></div></div>');
});
$(document).on('click','.remove_row', function(){
var row_id = $(this).attr('id');
$('#row'+row_id+'').remove();
});
});
$('select[name="madic"]').change(mediSum);
function mediSum(){
var elemente = $('select[name="madic"]').find('option:selected');
var desc1 = Number(elemente.data("price"));
var rate2 = $('.mrate').val(desc1);
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--- madicine row ----->
<div class="row col col-md-12 madi" id="mad" style="display: block;">
<br>
<div class="col col-md-4">
<select class="form-control item" name="madic" id="medicine" required>
<option value="" selected >Select Madicine</option>
<option value="1" data-price="125">Amoxline1</option>
<option value="2" data-price="163">Amoxline2</option>
<option value="3" data-price="723">Amoxline3</option>
<?php }} ?>
</select>
</div>
<div class="col col-md-2">
<input type="text" name="mrate[]" value="0" class="mrate form-control " id="mrate" readonly>
</div>
<div class="col col-md-1">
<input type="text" name="Qty[]" class="form-control Qty" value="1" id="Qty" >
</div>
<div class="col col-md-1">
<input type="text" name="mdiscount[]" class="form-control mdiscount" value="0" id="mdiscount" >
</div>
<div class="col col-md-2">
<input type="text" name="pack[]" class="form-control" placeholder="eg: Tab,box .." >
</div>
<div class="col col-md-1">
<button type="button" id="add" class="btn btn-success">+</button>
</div>
</div><!-- end medicines -->
Example of what I want when user select then data-price value display in next input field even when I add another row.

When you called
$('select[name="madic"]').change(mediSum);
you have specified that all select tags existent (at the time) in the document, having the name of madic should handle change events by calling mediSum. However, when such a select is created later, it does not have this handler. So, I recommend changing your code to:
$('select[name="madic"]:not(.initialized)').change(mediSum).addClass('initialized');
So, any select tags having the name of madic that were not initialized (we know that by the fact that they don't have the initialized class yet) will be associated with the given change handler and will receive the initialized class. Now, you have a feature that dynamically adds similar select tags. Those new tags will not have the initialized class, so running the same code when the add event happens as the one suggested above should solve your issue.

Related

How can I convert form data with multiple sections to json

I am trying to save data in html form as json. But only my last row is saved. The reason for this is probably because the names of the inputs in the two sections are the same.
But I want the json file like this:
{"name":"Name1","surname":"Surname1","gender":"f","birthDay":"15","birthMonth":"1","birthYear":"1995"},
{"name":"Name2","surname":"Surname2","gender":"m","birthDay":"20","birthMonth":"2","birthYear":"2020"}
But now output is:
{"name":"Name2","surname":"Surname2","gender":"m","birthDay":"20","birthMonth":"2","birthYear":"2020"}
function handleFormSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
const formJSON = Object.fromEntries(data.entries());
console.log(JSON.stringify(formJSON))
}
const form = document.querySelector('#example-form');
form.addEventListener('submit', handleFormSubmit);
<div class="container py-4">
<form id="example-form">
<div class="row">
<div class="col-md-12 p-0">
<div class="col-md-12 form_field_outer p-0" id="app">
<div class="row form_field_outer_row">
<div class="form-group col-md-2">
<input class="form-control w_90" id="name" name="name" placeholder="Name" type="text" value="" /></div>
<div class="form-group col-md-2">
<input class="form-control w_90" id="surname" name="surname" placeholder="Surname" type="text" value="" /></div>
<div class="form-group col-md-2">
<select class="form-control" id="gender" name="gender"><option disabled="disabled" selected="selected">Gender</option>
<option value="f">Female</option>
<option value="m">Male</option>
<option value="n">None.</option></select></div>
<div class="form-group col">
<input class="form-control w_90" id="birthDay" maxlength="2" name="birthDay" placeholder="Day" type="text" value="" /></div>
<div class="form-group col">
<select class="form-control" id="birthMonth" name="birthMonth">
<option disabled="disabled" selected="selected">Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
</div>
<div class="form-group col">
<input class="form-control w_90" id="birthYear" maxlength="4" name="birthYear" placeholder="Year" type="text" value="" /></div>
</div>
<br>
<div class="row form_field_outer_row">
<div class="form-group col-md-2">
<input class="form-control w_90" id="name" name="name" placeholder="Name" type="text" value="" /></div>
<div class="form-group col-md-2">
<input class="form-control w_90" id="surname" name="surname" placeholder="Surname" type="text" value="" /></div>
<div class="form-group col-md-2">
<select class="form-control" id="gender" name="gender"><option disabled="disabled" selected="selected">Gender</option>
<option value="f">Female</option>
<option value="m">Male</option>
<option value="n">None.</option></select></div>
<div class="form-group col">
<input class="form-control w_90" id="birthDay" maxlength="2" name="birthDay" placeholder="Day" type="text" value="" /></div>
<div class="form-group col">
<select class="form-control" id="birthMonth" name="birthMonth">
<option disabled="disabled" selected="selected">Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
</div>
<div class="form-group col">
<input class="form-control w_90" id="birthYear" maxlength="4" name="birthYear" placeholder="Year" type="text" value="" /></div>
</div>
</div>
</div>
</div>
<br>
<div class="col-md ml-0 mt-3 py-3">
<div class="col-md-12">
<button type="submit" id="submitId" class="btn btn-success float-right "><i class="fa fa-check-circle"></i> Submit</button>
</div>
</div>
</form>
</div>
How can I solve this?
Thanks for answers.
You have to have unique id and name values to your form elements.
So change the two occurences of:
<input id="surname" name="surname">
to something like this:
<input id="surname_0" name="person[0][surname]">
And the second occurence:
<input id="surname_1" name="person[1][surname]">
(I removed all other attributes to improve readability for my answer)

Scores of students adding up on one student's total score

There is a section in my school web app that allows me to add scores for all students of a specific class at once.
I recently added some codes that automatically calculates the sum of input values with javascript.
It works fine. Problem is, scores of all students are been added up as one to just one student at the top.
Please see image below
I want each student to have their own total score.
<?php }elseif($class_id >= 15 && $class_id <= 17){ ?>
<form action="<?php echo site_url('admin/mtprimary/assigngradeActionMT') ?>" method="POST" id="formSubjectTeacher">
<?php echo $this->customlib->getCSRF(); ?>
<div class="row">
<div class="col-lg-3">
<input type="hidden" name="class" value="<?php echo $class_id; ?>">
<input type="hidden" name="subject_id" value="<?php echo $subject_id; ?>">
</div>
<div class="col-lg-4">
<h4><strong><?php echo $session_name; ?></strong></h4>
</div>
</div>
<br>
<hr>
<?php foreach($students as $student){?>
<div class="row">
<div class="col-lg-3">
<div class="form-group">
<label>Student Name</label>
<input type="hidden" name="number[]" value="">
<input type="hidden" name="section_id" value="<?php echo $section_id; ?>">
<input type="hidden" name="session_id[]" value="<?php echo $student->session_id; ?>">
<input type="hidden" name="student_id[]" value="<?php echo $student->student_id; ?>">
<input type="hidden" name="class_id[]" value="<?php echo $class_id; ?>">
<input type="text" value="<?php echo $CI->GetStudentNameWithID($student->student_id); ?>" class="form-control " readonly>
</div>
</div>
<div class="col-lg-1">
<label>Test1 </label>
<input type="hidden" name="session_id[]" value="<?php echo $sessionID; ?>">
input type="number" name="mt_ca1[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="t2">
<label>Test2</label>
<input type="number" name="mt_ca2[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="assg">
<label>Test3</label>
<input type="number" name="mt_ca3[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1">
<label>Total</label>
<output id="result"></output>
</div>
</div>
<script>
const $inputs = $('input[type="number"]')
$inputs.change(function() {
var total = 0;
$inputs.each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
$('#result').html(total);
});
</script>
As has been pointed out, you have multiple elements with an id of result which is not allowed, you should use a class of result instead. But your main problem is that you need to qualify the inputs that you sum to get the total score for a student. You can do this by finding the parent div with class row for the input which changes, and then only sum the inputs that are children of that div. You can then store the total to the result output which is a child of that div:
const $inputs = $('input[type="number"]')
$inputs.change(function() {
var total = 0;
var parent = $(this).closest('.row');
parent.find('input[type="number"]').each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
parent.find('.result').html(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-3">
<div class="form-group">
<label>Student Name</label>
<input type="hidden" name="number[]" value="">
<input type="hidden" name="section_id" value="1">
<input type="hidden" name="session_id[]" value="5">
<input type="hidden" name="student_id[]" value="1">
<input type="hidden" name="class_id[]" value="1">
<input type="text" value="Bill" class="form-control " readonly>
</div>
</div>
<div class="col-lg-1">
<label>Test1 </label>
<input type="hidden" name="session_id[]" value="<?php echo $sessionID; ?>">
<input type="number" name="mt_ca1[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="t2">
<label>Test2</label>
<input type="number" name="mt_ca2[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="assg">
<label>Test3</label>
<input type="number" name="mt_ca3[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1">
<label>Total</label>
<output class="result"></output>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<div class="form-group">
<label>Student Name</label>
<input type="hidden" name="number[]" value="">
<input type="hidden" name="section_id" value="1">
<input type="hidden" name="session_id[]" value="5">
<input type="hidden" name="student_id[]" value="2">
<input type="hidden" name="class_id[]" value="1">
<input type="text" value="Mary" class="form-control " readonly>
</div>
</div>
<div class="col-lg-1">
<label>Test1 </label>
<input type="hidden" name="session_id[]" value="<?php echo $sessionID; ?>">
<input type="number" name="mt_ca1[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="t2">
<label>Test2</label>
<input type="number" name="mt_ca2[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1" id="assg">
<label>Test3</label>
<input type="number" name="mt_ca3[]" class="form-control input-sm rounded-0" value="0">
</div>
<div class="col-lg-1">
<label>Total</label>
<output class="result"></output>
</div>
</div>
The attribute id must be unique in a document, use class instead. First change the HTML with class.
From
<output id="result"></output>
To
<output class="result"></output>
In jQuery Change
$('#result').html(total);
To
$(this).parent().next().find('.result').text(total);
Please Note: It is good practice to use text() instead of html() if the the text is plain string (not htmlString).
I will also prefer input event instead of change to output the immediate changes by changing
$inputs.change(function() {
To
$inputs.on('input', function() {

Automatically calculate the sum of input values with javascript

I need some help in calculating the sum of the numbers a user has entered, and display it automatically. When the user delete one number the sum should also auto calculate.
$('.col-lg-1').change(function() {
var total = 0;
$('.col-lg-1').each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
$('#result').html(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-1">
<label>TEST 1 </label>
<input type="hidden" name="section_id" value="<?php echo $section_id; ?>">
<input type="hidden" name="session_id" value="<?php echo $session_id; ?>">
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
<input type="hidden" name="class_id" value="<?php echo $class_id; ?>">
<input type="number" name="mt_ca1" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1" id="t2">
<label>TEST 2</label>
<input type="number" name="mt_ca2" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1" id="assg">
<label>TEST 3</label>
<input type="number" name="mt_ca3" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1">
<label>TOTAL</label>
<output id="result"></output>
</div>
Almost there. You are targeting '.col-lg-1' which are divs, not inputs. You need to target the inputs in order to read their values.
const $inputs = $('input[type="number"]')
$inputs.change(function() {
var total = 0;
$inputs.each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
$('#result').html(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-1">
<label>TEST 1 </label>
<input type="hidden" name="section_id" value="<?php echo $section_id; ?>">
<input type="hidden" name="session_id" value="<?php echo $session_id; ?>">
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
<input type="hidden" name="class_id" value="<?php echo $class_id; ?>">
<input type="number" name="mt_ca1" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1" id="t2">
<label>TEST 2</label>
<input type="number" name="mt_ca2" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1" id="assg">
<label>TEST 3</label>
<input type="number" name="mt_ca3" class="form-control input-sm rounded-0" required>
</div>
<div class="col-lg-1">
<label>TOTAL</label>
<output id="result"></output>
</div>
.col-lg-1 is a DIV - you're attaching a change event and trying to get this.value from a DIV which will not work.
Instead, cache your inputs and (on "input" event) .reduce() their values into an integer:
jQuery($ => {
const $inp = $(".input-sm"); //PS: Use a more specific selector than this one
const $res = $("#result");
$inp.on("input", () => {
const total = $inp.get().reduce((acc, el) => (acc += parseInt(el.value, 10) || 0), 0);
$res.text(total);
});
});
<div>
<label>TEST 1 </label>
<input type="number" name="mt_ca1" class="inp form-control input-sm rounded-0" required value="0">
</div>
<div class="col-lg-1" id="t2">
<label>TEST 2</label>
<input type="number" name="mt_ca2" class="form-control input-sm rounded-0" required value="0">
</div>
<div class="col-lg-1" id="assg">
<label>TEST 3</label>
<input type="number" name="mt_ca3" class="form-control input-sm rounded-0" required value="0">
</div>
<div class="col-lg-1">
<label>TOTAL</label>
<output id="result"></output>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
your each element is number type and have same classes 'form-control', 'input-sm', & 'rounded-0'.
so either
$('input[type=number]').change(function() {
var total = 0;
$('input[type=number]').each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
$('#result').html(total);
});
or
$('.rounded-0').change(function() {
var total = 0;
$('.rounded-0').each(function() {
if ($(this).val() != '') {
total += parseInt($(this).val());
}
});
$('#result').html(total);
});
can be used.

Add row automatically when focused on last input in the form

I'm stuck on part of my project where user should just keep filling the form and new lines should be added automatically when user focused on last input in the form. I'm not forged in JS/jQ so maybe one of you could help me... It is working but still just from the 1st line, not from the duplicated ones. Thanks is advance
<form class="form-inline" method="post" action="loadin.php">
<!-- form header -->
<hr>
<div class="form-group">
<select class="form-control" name="vendor" id="vendor">
<?php
foreach($vendors_ as $v){
echo"<option value='".$v['ID']."'>".ucfirst($v['name'])."</option>";
}
?>
</select>
<input type="text" class="form-control" name="invoice" id="invoice" placeholder="Faktrura">
<input type="text" class="form-control" name="date" id="date" placeholder="Datum" value="<?php echo date("Y-m-d") ?>">
<button type="submit" name="LoadItems" class="btn btn-default"><i class="fa fa-check" aria-hidden="true"></i> Nahrát</button>
</div>
<hr>
<!-- form lines -->
<div class="duplicate" style="margin-bottom: 5px;">
<div class="form-group">
<input type="hidden" class="form-control cleanVal" name="row[]" id="row">
<select class="form-control" name="category[]" id="category">
<?php
foreach($types_ as $t){
echo"<option value='".$t['ID']."'>".ucfirst($t['name'])."</option>";
}
?>
</select>
<input type="text" class="form-control cleanVal" name="item[]" id="item" placeholder="Položka">
<input type="text" class="form-control cleanVal" name="package[]" id="package" placeholder="Balení">
<input type="text" class="form-control cleanVal" name="amount[]" id="amount" placeholder="Množství">
<input type="text" class="form-control cleanVal" name="price[]" id="price" placeholder="Cena">
<input type="text" class="form-control cleanVal" name="atest[]" id="atest" placeholder="Atest">
<input type="text" class="form-control cleanVal" name="batch[]" id="batch" placeholder="Sarže">
<input type="text" class="form-control cleanVal" name="expire[]" id="expire" placeholder="Expirace" style="width:80px">
<input type="text" class="form-control cleanVal x" name="vat[]" id="vat" placeholder="DPH" style="width:45px">
</div>
</div>
</form>
$(".duplicate:last input").focus(function() {
count++;
var $clone = $('.duplicate:last').clone();
$clone.find("input,select").each(function(){
$(this).attr({
id: $(this).attr("id") + count,
});
});
$("form").append($clone);
$(".duplicate:last .cleanVal").val('');
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
As last element is being changed every time new elements are appended, listen the event on the parent body or any other fixed parent.
var count = 0;
$('body').on('focus', ".duplicate:last input", function() {
count++;
var $clone = $('.duplicate:last').clone();
$clone.find("input,select").each(function() {
$(this).attr({
id: $(this).attr("id") + count,
});
});
$("form").append($clone);
$(".duplicate:last .cleanVal").val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form class="form-inline" method="post" action="loadin.php">
<hr>
<div class="form-group">
<select class="form-control" name="vendor" id="vendor">
</select>
<input type="text" class="form-control" name="invoice" id="invoice" placeholder="Faktrura">
<input type="text" class="form-control" name="date" id="date" placeholder="Datum" value="">
<button type="submit" name="LoadItems" class="btn btn-default"><i class="fa fa-check" aria-hidden="true"></i> Nahrát</button>
</div>
<hr>
<div class="duplicate" style="margin-bottom: 5px;">
<div class="form-group">
<input type="hidden" class="form-control cleanVal" name="row[]" id="row">
<select class="form-control" name="category[]" id="category">
</select>
<input type="text" class="form-control cleanVal" name="item[]" id="item" placeholder="Položka">
<input type="text" class="form-control cleanVal" name="package[]" id="package" placeholder="Balení">
<input type="text" class="form-control cleanVal" name="amount[]" id="amount" placeholder="Množství">
<input type="text" class="form-control cleanVal" name="price[]" id="price" placeholder="Cena">
<input type="text" class="form-control cleanVal" name="atest[]" id="atest" placeholder="Atest">
<input type="text" class="form-control cleanVal" name="batch[]" id="batch" placeholder="Sarže">
<input type="text" class="form-control cleanVal" name="expire[]" id="expire" placeholder="Expirace" style="width:80px">
<input type="text" class="form-control cleanVal x" name="vat[]" id="vat" placeholder="DPH" style="width:45px">
</div>
</div>
</form>
Fiddle Demo
You must define your focus event as bellow:
$('body').on('focus', ".duplicate:last input", function() {
// codes here
}

Unable to print the $length variable? Trying to input data from cloned forms

My code is below. I am have arrays declared in html input tag name field, title[], first_name[], last_name[], email_address[], twitter_handle[].
I have declared them all arrays for the sake of form cloning that I am doing in .js file.
Now, I am trying to enter the data from form in to database.
I am using the foreach to manage the arrays, I also took a $length variable which will give me the number of form cloning worked.
No matter how many times I clone the form, only the first form gets printed.
Please help.
My code is below:
if(isset($_POST['title']) && isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email_address']) && isset($_POST['twitter_handle'])){
$length=0;
foreach($_POST['title'] as $key=>$value){
$title[$key]=$value;
$length=$length + 1;
echo '$key: '.$key.' '.$length;
//print_r($value);
}
foreach($_POST['first_name'] as $key=>$value){
$first_name[$key]=$value;
}
foreach($_POST['last_name'] as $key=>$value){
$last_name[$key]=$value;
}
foreach($_POST['email_address'] as $key=>$value){
$email_address[$key]=$value;
}
foreach($_POST['twitter_handle'] as $key=>$value){
$twitter_handle[$key]=$value;
}
echo '$lenght : '.$length.' ';
for($i=0;$i<$length;$i++){
print_r($first_name[$i]);
}
}
..................
Just for reference this is my html code:
<form action="<?php $_SERVER['PHP_SELF']?>" method="POST" id="sign-up_area" role="form">
<label class="label_ttl control-label" for="title">Title:</label>
<div class="form-group">
<select class="select_ttl form-control" name="title[]" id="title">
<option value="" selected="selected" disabled="disabled">Select your title</option>
<option value="Dr.">Dr.</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Ms.">Ms.</option>
<option value="Sir">Sir</option>
</select>
</div>
<!-- Text input-->
<div class="form-group">
<label class="label_fn control-label" for="first_name">First name:</label>
<input id="first_name" name="first_name[]" type="text" placeholder="" class="input_fn form-control" required>
<p class="help-block">This field is required.</p>
</div>
<!-- Text input-->
<div class="form-group">
<label class="label_ln control-label" for="last_name">Last name:</label>
<input id="last_name" name="last_name[]" type="text" placeholder="" class="input_ln form-control">
</div>
<div class="form-group">
<label class="label_email control-label" for="email_address">Email:</label>
<input id="email_address" name="email_address[]" type="text" placeholder="example#example.com" class="input_email form-control">
</div>
<!-- Prepended text-->
<label class="label_twt control-label" for="institution">Enter Institution / Organization:</label>
<div class="input-group form-group">
<input id="twitter_handle" name="twitter_handle[]" class="input_twt form-control" placeholder="" type="text">
</div>
<!-- Text input-->
</div><!-- end #entry1 -->
<!-- Button (Double) -->
<p>
<button type="button" id="btnAdd" name="btnAdd" class="btn btn-info">add section</button>
<button type="button" id="btnDel" name="btnDel" class="btn btn-danger">remove section above</button>
</p>
<!-- Button -->
<p>
<button id="submit_button" name="submit_button" class="btn btn-primary">Submit</button>
</p>
</fieldset>
</form>
<?php
if(isset($_POST['title']) && isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email_address']) && isset($_POST['twitter_handle'])){
$length=0;
foreach($_POST['title'] as $key=>$value){
$title[$key]=$value;
$length = $length + 1;
//echo '$key: '.$key.' '.$length;
//print_r($value);
}
foreach($_POST['first_name'] as $key=>$value){
$first_name[$key]=$value;
}
foreach($_POST['last_name'] as $key=>$value){
$last_name[$key]=$value;
}
foreach($_POST['email_address'] as $key=>$value){
$email_address[$key]=$value;
}
foreach($_POST['twitter_handle'] as $key=>$value){
$twitter_handle[$key]=$value;
}
echo '$lenght : '.$length.' ';
for($i=0;$i<$length;$i++){
echo ($first_name[$i])."<br/>";
}
}
?>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<form action="<?php $_SERVER['PHP_SELF']?>" method="POST" id="sign-up_area" role="form">
<div class="form" id="form_1">
<label class="label_ttl control-label" for="title">Title:</label>
<div class="form-group">
<select class="select_ttl form-control" name="title[]" id="title">
<option value="" selected="selected" disabled="disabled">Select your title</option>
<option value="Dr.">Dr.</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Ms.">Ms.</option>
<option value="Sir">Sir</option>
</select>
</div>
<!-- Text input-->
<div class="form-group">
<label class="label_fn control-label" for="first_name">First name:</label>
<input id="first_name" name="first_name[]" type="text" placeholder="" class="input_fn form-control" required>
<p class="help-block">This field is required.</p>
</div>
<!-- Text input-->
<div class="form-group">
<label class="label_ln control-label" for="last_name">Last name:</label>
<input id="last_name" name="last_name[]" type="text" placeholder="" class="input_ln form-control">
</div>
<div class="form-group">
<label class="label_email control-label" for="email_address">Email:</label>
<input id="email_address" name="email_address[]" type="text" placeholder="example#example.com" class="input_email form-control">
</div>
<!-- Prepended text-->
<label class="label_twt control-label" for="institution">Enter Institution / Organization:</label>
<div class="input-group form-group">
<input id="twitter_handle" name="twitter_handle[]" class="input_twt form-control" placeholder="" type="text">
</div>
<!-- Text input-->
</div><!-- end #entry1 -->
<!-- Button (Double) -->
<p>
<button type="button" id="btnAdd" name="btnAdd" class="btn btn-info">add section</button>
<button type="button" id="btnDel" name="btnDel" class="btn btn-danger">remove section above</button>
</p>
<!-- Button -->
<p>
<button id="submit_button" name="submit_button" class="btn btn-primary">Submit</button>
</p>
</fieldset>
</div>
</form>
<script type="text/javascript">
$('#btnAdd').click(function(){
var form_length = $(".form").length;
$('#form_'+form_length).clone().prop({ id: "form_"+parseInt(form_length+1)}).insertAfter('#form_'+form_length);
});
$('#btnDel').click(function(){
var form_length = $(".form").length;
if(form_length == 1){
alert("One form must exist!");
}else{
$('.form').last().remove();
}
});
</script>

Categories