jQuery/PHP dynamic form submission - javascript

I'm looking for a way to submit multiple dynamic form fields in a single submission.
Each row of data when submitted will share certain attributes:
job id, client, type of work.
While also keeping their own independent variables:
role, name, tvl, start date, end date, start time, end time.
I think my solution will either require a for loop or the use of multi dimensional arrays (maybe both?) but I can't quite figure out where in my code to implement that or how to do so.
At the moment - only 1 "employee" is showing up in my database - typically the last entry made in the "details" div.
Here is the code:
HTML
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<head>
</head>
<body>
<form method="POST" action="include/ajax.inc.php" class="ajax">
<h2>Job Details</h2>
<br>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Job ID</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="a" id="a">
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Client</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="b" id="b">
<option value="" disabled selected>Select</option>
<option value="OPTION1" name="OPTION1">OPTION1</option>
<option value="OPTION2" name="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Type of Work</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="c" id="c">
<option value="" disabled selected>Select</option>
<option value="OPTION1" name="OPTION1">OPTION1</option>
<option value="OPTION2" name="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<h2>Employee Details</h2>
<button class="btn btn-lg btn-primary btn-rounded m-sm" id="add">
<small>ADD EMPLOYEE</small>
</button>
<!--- ADD EMPLOYEES --->
<div class="ibox" id="details" name="details[]">
<div class="ibox-content">
<div class="container">
<div class="row">
<div class="col">
<label class="form-label">Position</label>
<select class="form-control" type="text" name="d" id="d">
<option value="" disabled selected>Select</option>
<option value="ROLE1" name="SPV">ROLE1</option>
<option value="ROLE2" name="REG">ROLE2</option>
</select>
</div>
<div class="col">
<label class="form-label">Name</label>
<input type="text" class="form-control" name="e" id="e">
</div>
<div class="col">
<label class="form-label">TVL</label>
<input type="text" class="form-control" name="f" id="f">
</div>
<div class="col">
<label class="form-label">Start Date</label>
<input type="date" class="form-control" name="g" id="g">
</div>
<div class="col">
<label class="form-label">End Date</label>
<input type="date" class="form-control" name="h" id="h">
</div>
<div class="col">
<label class="form-label">Start Time</label>
<input type="time" class="form-control" name="i" id="i">
</div>
<div class="col">
<label class="form-label">End Time</label>
<input type="time" class="form-control" name="j" id="j">
</div>
<div class="col text-right m-t-lg">
</div>
</div>
</div>
</div>
</div>
<!--- ADD EMPLOYEES END --->
<div class="hr-line-dashed"></div>
<button type="submit" class="btn btn-primary btn-med" name="submit">Submit</button>
</form>
<!-- SCCRIPT-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
JS
main.js
$(document).ready(function(){
var html = ' <div class="ibox" id="details" name="details[i]"> <div class="ibox-content"> <div class="container"> <div class="row"> <div class="col"> <label class="form-label">Position</label> <select class="form-control" type="text" name="d" id="d"> <option value="" disabled selected>Select</option> <option value="SPV" name="SPV">SPV</option> <option value="REG" name="REG">REG</option> </select> </div> <div class="col"> <label class="form-label">Name</label> <input type="text" class="form-control" name="e" id="e"> </div> <div class="col"> <label class="form-label">TVL</label> <input type="text" class="form-control" name="f" id="f"> </div> <div class="col"> <label class="form-label">Start Date</label> <input type="date" class="form-control" name="g" id="g"> </div> <div class="col"> <label class="form-label">End Date</label> <input type="date" class="form-control" name="h" id="h"> </div> <div class="col"> <label class="form-label">Start Time</label> <input type="time" class="form-control" name="i" id="i"> </div> <div class="col"> <label class="form-label">End Time</label> <input type="time" class="form-control" name="j" id="j"> </div> <div class="col text-right m-t-lg"> </div> <div class="col text-right m-t-lg"> <button class="btn btn-sm btn-rounded btn-danger" id="remove"> <i class="fa fa-times"></i> </button> </div></div> </div> </div> </div>'
// Add rows to the form
$(function() {
$('#add').click(function(e) {
$('#details').append(html);
e.preventDefault();
});
// Remove rows from the form
$(this).on('click', '#remove', function(e) {
$(this).closest('#details').remove();
});
});
});
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[id]').each(function(index, value){
var that = $(this),
name = that.attr('id'),
value = that.val();
data[name] = value;
});
$.ajax ({
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
PHP
ajax.inc.php
<?php
include 'form.dbh.php'; {
$jobid = mysqli_real_escape_string($conn,$_POST['a']);
$client = mysqli_real_escape_string($conn,$_POST['b']);
$type = mysqli_real_escape_string($conn,$_POST['c']);
$role = mysqli_real_escape_string($conn,$_POST['d']);
$name = mysqli_real_escape_string($conn,$_POST['e']);
$tvl = mysqli_real_escape_string($conn,$_POST['f']);
$sdate = mysqli_real_escape_string($conn,$_POST['g']);
$edate = mysqli_real_escape_string($conn,$_POST['h']);
$stime = mysqli_real_escape_string($conn,$_POST['i']);
$etime = mysqli_real_escape_string($conn,$_POST['j']);
$sql = "INSERT INTO timesheets(jobid, client, type, role, name, tvl, sdate, edate, stime, etime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)){
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, 'ssssssssss', $jobid, $client, $type, $role, $name, $tvl, $sdate, $edate, $stime, $etime);
mysqli_stmt_execute($stmt);
}
header("Location:../index.php?success");
}
?>
Does anyone have an idea? or any suggestions?

Consider the following.
$(function() {
var html = ' <div class="ibox" id="details" name="details[i]"> <div class="ibox-content"> <div class="container"> <div class="row"> <div class="col"> <label class="form-label">Position</label> <select class="form-control" type="text" name="d" id="d"> <option value="" disabled selected>Select</option> <option value="SPV" name="SPV">SPV</option> <option value="REG" name="REG">REG</option> </select> </div> <div class="col"> <label class="form-label">Name</label> <input type="text" class="form-control" name="e" id="e"> </div> <div class="col"> <label class="form-label">TVL</label> <input type="text" class="form-control" name="f" id="f"> </div> <div class="col"> <label class="form-label">Start Date</label> <input type="date" class="form-control" name="g" id="g"> </div> <div class="col"> <label class="form-label">End Date</label> <input type="date" class="form-control" name="h" id="h"> </div> <div class="col"> <label class="form-label">Start Time</label> <input type="time" class="form-control" name="i" id="i"> </div> <div class="col"> <label class="form-label">End Time</label> <input type="time" class="form-control" name="j" id="j"> </div> <div class="col text-right m-t-lg"> </div> <div class="col text-right m-t-lg"> <button class="btn btn-sm btn-rounded btn-danger" id="remove"> <i class="fa fa-times"></i> </button> </div></div> </div> </div> </div>'
$('#add').click(function(e) {
$('#details').append(html);
e.preventDefault();
});
// Remove rows from the form
$(this).on('click', '#remove', function(e) {
$(this).closest('#details').remove();
});
$('form.ajax').on('submit', function(e) {
e.preventDefault();
var that = $(this),
u = that.attr('action'),
t = that.attr('method'),
d = {};
that.find('[id]').each(function(i, el) {
d[$(el).attr("id")] = $(el).val();
});
$.ajax({
url: u,
type: t,
data: d,
success: function(response) {
console.log(response);
}
});
return false;
});
});
This cleans up some of the issues you are seeing. When using .each() you will have an Index and Element, not a Value.
Update
The code above will submit all data based on the form.ajax selector. When you have only one section of details in the form, that is all the data that will be submitted. If you add your HTML, you cause an HTML/JS issue where the ID attributes of the elements are no longer Unique. All IDs must be unique.
Consider ignoring the IDs and make use of name attribute instead. When you gather the data, for d through j, these would need to be Arrays, since these are the items that repeat.
Consider the following.
$(function() {
function getData(f) {
var myData = {
a: $("[name='a']", f).val(),
b: $("[name='b']", f).val(),
c: $("[name='c']", f).val(),
d: [],
e: [],
f: [],
g: [],
h: [],
i: [],
j: []
};
var k, v;
$("[name]", f).each(function(i, el) {
k = $(el).attr("name");
v = $(el).val();
if (i > 2) {
myData[k].push(v);
}
});
console.log(myData);
return myData;
}
$('#add').click(function(e) {
var html = $("#details > .ibox-content:eq(0)").clone(true);
$(".col:last", html).html("<button class='btn btn-sm btn-rounded btn-danger remove' id='remove-" + $(".ibox-content").length + "'> <i class='fa fa-times'></i> </button>");
$(".ibox-content:last").after(html);
e.preventDefault();
});
$("#details").on('click', '.remove', function(e) {
$(this).closest('.ibox-content').remove();
});
$("form.ajax").submit(function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: getData(this),
success: function(response) {
console.log(response);
}
});
});
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="include/ajax.inc.php" class="ajax">
<h2>Job Details</h2>
<br>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Job ID</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="a" id="a">
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Client</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="b" id="b">
<option value="" disabled selected>Select</option>
<option value="OPTION1">OPTION1</option>
<option value="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Type of Work</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="c" id="c">
<option value="" disabled selected>Select</option>
<option value="OPTION1">OPTION1</option>
<option value="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<h2>Employee Details</h2>
<button class="btn btn-lg btn-primary btn-rounded m-sm" id="add"><small>ADD EMPLOYEE</small></button>
<!--- ADD EMPLOYEES --->
<div id="details" class="ibox">
<div class="ibox-content">
<div class="container">
<div class="row">
<div class="col">
<label class="form-label">Position</label>
<select class="form-control" type="text" name="d" id="d">
<option value="" disabled selected>Select</option>
<option value="ROLE1">ROLE1</option>
<option value="ROLE2">ROLE2</option>
</select>
</div>
<div class="col">
<label class="form-label">Name</label>
<input type="text" class="form-control" name="e" id="e">
</div>
<div class="col">
<label class="form-label">TVL</label>
<input type="text" class="form-control" name="f" id="f">
</div>
<div class="col">
<label class="form-label">Start Date</label>
<input type="date" class="form-control" name="g" id="g">
</div>
<div class="col">
<label class="form-label">End Date</label>
<input type="date" class="form-control" name="h" id="h">
</div>
<div class="col">
<label class="form-label">Start Time</label>
<input type="time" class="form-control" name="i" id="i">
</div>
<div class="col">
<label class="form-label">End Time</label>
<input type="time" class="form-control" name="j" id="j">
</div>
<div class="col text-right m-t-lg">
</div>
</div>
</div>
</div>
</div>
<!--- ADD EMPLOYEES END --->
<div class="hr-line-dashed"></div>
<button type="submit" class="btn btn-primary btn-med">Submit</button>
</form>
You may notice, only specific elements have the name attribute now. DIV elements should not use name and the same goes for OPTION. DIV is not a part of a Form. OPTION is a element part of SELECT which is the parent container and the form element, this should have name.
Your PHP will get a complex payload of data. For example:
{
"a": "2020",
"b": "OPTION1",
"c": "OPTION2",
"d": [
"ROLE1",
"ROLE2"
],
"e": [
"Bob",
"Nancy"
],
"f": [
"1",
"2"
],
"g": [
"2020-10-12",
"2020-10-12"
],
"h": [
"2020-10-16",
"2020-10-16"
],
"i": [
"08:00",
"08:00"
],
"j": [
"12:00",
"12:00"
]
}
You will need to adjust your PHP to handle this new data format.

Related

Copy data using checkbox not working in repeater field

On the 1st image link, I have enter the required data in the first tab.
On the 2nd image link, when I go to second tab and click on checkbox it copy data from 1st tab and show in the 2nd tab form
On the 3rd image link, when I repeat the form and also when click on check box the data did not show in the respective field.
$(document).ready(function() {
$(".repeater").repeater({
defaultValues: {
//"text-input": "foo"
},
show: function() {
$(this).slideDown();
},
hide: function(deleteElement) {
if (confirm("Are you sure you want to delete this element?")) {
$(this).slideUp(deleteElement);
}
},
ready: function(setIndexes) {
//$dragAndDrop.on('drop', setIndexes);
},
repeaters: [
{
selector: ".inner-repeater"
}
]
});
});
function myFunction() {
var checkBox = document.getElementById("single_checkbox");
var door_no = document.getElementById("doorno");
var street_name = document.getElementById("streetname");
var client_area = document.getElementById("area");
var client_statename = document.getElementById("statename");
var client_dist = document.getElementById("distname");
var client_city = document.getElementById("city");
var client_pincode = document.getElementById("pincode");
var dr_number = document.getElementById("doornos");
var contact_street = document.getElementById("streetnames");
var contact_area = document.getElementById("contactarea");
var contact_state = document.getElementById("statenamecontact");
var contact_dist = document.getElementById("contactdist");
var contact_city = document.getElementById("contactcity");
var contact_pincode = document.getElementById("pincode_contact");
if (checkBox.checked == true){
dr_number.value=door_no.value;
contact_street.value=street_name.value;
contact_area.value=client_area.value;
contact_state.value=client_statename.value;
contact_dist.value=client_dist.value;
contact_city.value=client_city.value;
contact_pincode.value=client_pincode.value;
} else {
dr_number.value="";
contact_street.value="";
contact_area.value="";
contact_state.value="";
contact_dist.value="";
contact_city.value="";
contact_pincode.value="";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.repeater/1.2.1/jquery.repeater.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js"></script>
<div class="row match-height">
<div class="col-md-12">
<div class="">
<div class=" collapse show">
<div class="">
<form action="clientinsert2" method="post" enctype="multipart/form-data">
<div class="">
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" href="#home">Client</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#menu1">Client Contact</a>
</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div id="home" class="tab-pane active pd_0"><br>
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="">Client Name </label>
<input type="text" class="form-control" value="" name="clientname">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="">Phone Number</label>
<input type="text" class="form-control" value="" name="phone">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="">Door Number</label>
<input type="text" class="form-control" value="" id="doorno" name="doorno">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="issueinput4">Street Name</label>
<input type="text" class="form-control" value=""id="streetname" name="streetname">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="">Area</label>
<input type="text" class="form-control" id="area" name="area" value="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="">State</label>
<select class="form-control" name="State" id="statename" value="">
<option>Select</option>
<option>odisha</option>
<option>Bihar</option>
<option>Assam</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="">District</label>
<select class="form-control" id="distname" name="districtname" value="">
<option>Select</option>
<option>jajpur</option>
<option>puri</option>
<option>cuttack</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="">City</label>
<select class="form-control" name="cityname" id="city" value="">
<option>Select</option>
<option>Bhubaneswar</option>
<option>Bari</option>
<option>Mangalpur</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="">Pincode</label>
<input type="text" class="form-control" name="pincode" value="" id="pincode">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Status</label>
<select class="form-control" name="status" value="">
<option selected>Please Select Status</option>
<option value="1">Active</option>
<option value="2">Inactive</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Logo</label>
<input type="file" class="form-control" name="client_logo">
</div>
</div>
</div>
</div>
</div>
<!-- client contact form start-->
<div id="menu1" class="tab-pane fade pd_0"><br>
<div class="form-group mb-2 repeater">
<div data-repeater-list="outer-list">
<div data-repeater-item>
<div class="row mb-1">
<div class="col-md-6">
<div class="form-group">
<label for="">Contact Person </label>
<input type="text" class="form-control" name="contactname">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="">Contact Person Phone</label>
<input type="text" class="form-control" name="contactphone">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Mail</label>
<input type="email" class="form-control" name="contactmail">
</div>
</div>
<!-- <div class="col-md-4">
<div class="form-group">
<label for="">Client Primary Spoc</label>
<div class="skin skin-square">
<input type="checkbox"
id="single_checkbox1" name="client_contact_primary_spoc"
value="checked">
<label for="single_checkbox1">checked</label>
</div>
</div>
</div> -->
<div class="col-md-4">
<div class="form-group">
<label for="">Designation</label>
<input type="text" class="form-control" name="designation">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Status</label>
<select class="form-control" name="status">
<option selected>Please Select Status</option>
<option value="1">Active</option>
<option value="2">Inactive</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Client Branch</label>
<select class="form-control" name="clientbranch">
<option>Select</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Corporate Address</label>
<div class="">
<input type="checkbox" value="1" id="single_checkbox"
name="checkbox" onclick="myFunction()">
<label for="">checked
</label>
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Door Number</label>
<input type="text" class="form-control" name="doorno" id="doornos">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="issueinput4">Street Name</label>
<input type="text" class="form-control" name="streetname" id="streetnames">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Area</label>
<input type="text" class="form-control" name="area" id="contactarea">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">State</label>
<select class="form-control" name="State"
id="statenamecontact">
<option>Select</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">District</label>
<select class="form-control" name="districtname"
id="contactdist">
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">City</label>
<select class="form-control" name="cityname"
id="contactcity">
<option>Select</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Pincode</label>
<input type="text" class="form-control" name="pincode" id="pincode_contact">
</div>
</div>
<div class="col-12">
<button type="button" data-repeater-delete
class="btn btn-icon btn-danger mr-1"><i
class="ft-x"></i></button>
</div>
</div>
</div>
</div>
<button type="button" data-repeater-create id="repeater-button"
class="btn btn-info">
<i class="ft-plus"></i> Add new file
</button>
</div>
<div class="form-actions">
<span id="hide">
<a href="/client"><input type="button" class="btn btn-warning"
value="Back"></a>
</span>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
<!-- Tab panes -->
</div>
</div>
</div>
</div>
</div>
<!-- Form wizard with icon tabs section end -->
</div>

how do I get a value if I click on one of the divs that have been appended?

I have a data that will be posted to a form but there is data that I can't take how to retrieve the "excess bag amount" so I can post it?
this is my controller
function getAirlinesById(idAirlines) {
$.ajax({
dataType: 'json',
type: "POST",
url: '{{route('get-baggage-airlines')}}',
data:"airlines_id="+idAirlines,
success: function(response){
console.log(response);
$("#baggageAirline").empty();
for(let i=0;i<response.length;i++){
let category = response[i].baggage.category;
switch(category) {
case 1:
category = "KG";
break;
case 2:
category = "PCS";
break;
};
$("#baggageAirline").append('<div class="col-3 list-baggage"><img src="{{asset("assets/image/baggage.png")}}" alt="" width="80px"><p class="baggage-amount">'+response[i].baggage.max_range+' '+category+'</p><input type="checkbox"><p class="text-center">'+response[i].currency_symbol+' '+response[i].price_in_SGD+'</p></div>');
}
}
});
}
I have tried to get the selected bag amount for me to post to a form, but the bag amount and price are not sent
$post = array(
"AIRLINES_ID" =>$input['airlines'],
"AIRLINES_NAME" =>$input['airlinesName'],
"AIRPORT_ID" =>$input['departure'],
"AIRPORT_NAME" =>$input['departureName'],
"FLIGHT_NO" =>$input['code'],
"PNR_TICKET" =>$input['pnr_ticket'],
"BAG_AMOUNT" =>$input['baggage-airlines'],
"PRICE" =>$input['price'],
"DEPARTURE_DATE" =>$input['date'],
"DEPARTURE_TIME" =>$input['time'],
"MEMBER_ID" => $id
);
this is the html form for me to post to the controller
<form action="{{route('book-baggage-post')}}" method="POST" id="formPostBaggage">
#csrf
<div class="container-fluid">
<div class="row">
<div class="col-12">
<label for=""><p class="mb-0">Airlines</p></label>
<select id="airlines_id" name="airlines" onchange="getName(this.options[this.selectedIndex].getAttribute('data-name'))" class="select2-input-custome" required>
<option value=""></option>
</select>
<input type="hidden" name="airlinesName" id="airlinesName">
</div>
<div class="col-12">
<p>Flight No</p>
</div>
<div class="col-4">
<div class="form-group">
<select class="form-control" name="code" id="codeAirline" style="background-color:#dcdcdc;">
<option value="disable"></option>
</select>
</div>
</div>
<div class="col-8 pl-0">
<div class="form-group">
<input type="text" class="form-control" name="flight_no" id="" placeholder="Flight No" style="background-color:#dcdcdc;">
</div>
</div>
<div class="col-12 clearfix">
<label for=""><p class="mb-0">Departure airport</p></label>
<select id="departure" name="departure" onchange="getNameDeparture(this.options[this.selectedIndex].getAttribute('data-name'))" class="select2-input-custome" required>
<option value=""></option>
</select>
<input type="hidden" name="departureName" id="departureName">
</div>
<div class="col-12">
<div class="form-group">
<label for="">PNR/Ticket No</label>
<input type="text" class="form-control"name="pnr_ticket" id="" placeholder="PNR/Ticket No" style="background-color:#dcdcdc;" required>
</div>
</div>
<div class="col-12">
<p>Departure Date Time</p>
</div>
<div class="col-6">
<div class="form-group">
<input type="text" class="form-control" name="date" id="datepicker" placeholder="Date" style="background-color:#dcdcdc;" required>
</div>
</div>
<div class="col-6">
<div class="form-group">
<input type="text" class="form-control" name="time" id="timepicker" placeholder="Time" style="background-color:#dcdcdc;" required>
</div>
</div>
<div class="col-12">
<p>Excess Bag Amount Required</p>
<div class="row" id="baggageAirline">
</div>
</div>
<div class="col-12">
<br>
<center>
<a href="{{route('passanger')}}">
<button type="submit" class="btn btn-default btn-book btn-block">
<p class="mb-0">NEXT</p>
</button>
</a>
</center>
</div>
</div>
</div>
</form>

Getting all form values and keys in 1 object [duplicate]

I have an HTML form, it's a pretty simple form, there's only 4 values that are required. It looks like this.
$form.addEventListener('submit', (event) => {
event.preventDefault()
const formData = new FormData(event.target)
// log our form object
console.log(formData)
event.target.reset()
})
<form id="heatmap-form">
<div class="form-row text-center">
<div class="form-group col">
<label for="parameter">Parameter</label>
<span class="asterisk_input"></span>
<select name="parameter" id="parameter" class="custom-select">
<option selected>Select a parameter</option>
<option value="air_temperature">Air humidity</option>
<option value="air_pressure">Air temperature</option>
<option value="air_humidity">Air pressure</option>
</select>
</div>
<div class="form-group col">
<label for="unit">Unit</label>
<span class="asterisk_input"></span>
<input name="unit" type="text" class="form-control" id="unit" placeholder="C, F, %, hPa etc" required>
</div>
<div class="form-group col">
<label for="height">Height</label>
<span class="asterisk_input"></span>
<input name="height" type="text" class="form-control" id="height" placeholder="In CM format" required>
</div>
<div class="form-group col">
<label for="startTime">Start time</label>
<span class="asterisk_input"></span>
<input name="startTime" type="datetime-local" class="form-control" id="startTime" placeholder="time" required>
</div>
</div>
<button id="optional-button" type="button" class="text-center my-4 btn btn-large btn-secondary">Show optional parameters</button>
<div id="optional-form" class="hidden form-row text-center optional-form">
<div class="form-group col-md-2">
<label for="endTime">End Time</label>
<input name="endTime" type="datetime-local" class="form-control" id="endTime">
</div>
<div class="form-group col-md-2">
<label for="maxValue">Max value</label>
<input name="maxValue" type="text" value=0 class="form-control" id="maxValue">
</div>
<div class="form-group col-md-2">
<label for="minValue">Min value</label>
<input name="minValue" type="text" value=0 class="form-control" id="minValue">
</div>
<div class="form-group col-md-2">
<label for="frameAmount">Number of frames</label>
<input name="frameAmount" type="text" value=10 placeholder="10" class="form-control" id="frameAmount">
</div>
<div class="form-group col-md-2">
<label for="translation">Translation</label>
<input name="translation" type="text" class="form-control" id="translation" placeholder="x">
</div>
<div class="form-group col-md-2">
<label class="text-center" for="linearInterpolation">Power of linear interpolation</label>
<input name="linearInterpolation" type="text" value=5 class="form-control" id="linearInterpolation">
</div>
<div class="form-group col-md-2">
<label for="omitted">list of omitted sensors</label>
<input name="omitted" type="text" class="form-control" id="omitted" placeholder="format eg. L4, L3, etc" value="">
</div>
</div>
<div class="d-flex flex-row justify-content-center">
<button id="form-submit" type="submit" class="text-center btn btn-primary">Submit</button>
</div>
</form>
And here is my JavaScript $form.addEventListener('submit', (event) => { event.preventDefault() const formData = new FormData(event.target) // log our form object console.log(formData) event.target.reset() })
In my console log, why aren't I getting my form data object with properties and values on it that are set to the name value of my inputs as keys and values of the inputs as values? Instead I'm just getting an empty form data object.
Your naming convention of $form is common to indicate the use of jQuery. If that is the case, then you don't have a proper jQuery reference to your form and, even if you did, you aren't making a proper jQuery configuration of the event callback.
Even if you are not using jQuery, then $form isn't a proper reference to your form, which has an id=heatmap-form.
Also, you don't get your actual form field values directly from a FormData object. You have to access the data with one of the many properties/methods of a FormData instance.
let $form = document.querySelector("form");
$form.addEventListener('submit', (event) => {
event.preventDefault()
const formData = new FormData(event.target)
// Loop over the key/value pairs contained in the FormData object
// the .entries() method returns an enumerable for us to loop over
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]); // Get the key and the value
}
event.target.reset();
})
<form id="heatmap-form">
<div class="form-row text-center">
<div class="form-group col">
<label for="parameter">Parameter</label>
<span class="asterisk_input"></span>
<select name="parameter" id="parameter" class="custom-select">
<option selected>Select a parameter</option>
<option value="air_temperature">Air humidity</option>
<option value="air_pressure">Air temperature</option>
<option value="air_humidity">Air pressure</option>
</select>
</div>
<div class="form-group col">
<label for="unit">Unit</label>
<span class="asterisk_input"></span>
<input name="unit" type="text" class="form-control" id="unit" placeholder="C, F, %, hPa etc" required>
</div>
<div class="form-group col">
<label for="height">Height</label>
<span class="asterisk_input"></span>
<input name="height" type="text" class="form-control" id="height" placeholder="In CM format" required>
</div>
<div class="form-group col">
<label for="startTime">Start time</label>
<span class="asterisk_input"></span>
<input name="startTime" type="datetime-local" class="form-control" id="startTime" placeholder="time" required>
</div>
</div>
<button id="optional-button" type="button" class="text-center my-4 btn btn-large btn-secondary">Show optional parameters</button>
<div id="optional-form" class="hidden form-row text-center optional-form">
<div class="form-group col-md-2">
<label for="endTime">End Time</label>
<input name="endTime" type="datetime-local" class="form-control" id="endTime">
</div>
<div class="form-group col-md-2">
<label for="maxValue">Max value</label>
<input name="maxValue" type="text" value=0 class="form-control" id="maxValue">
</div>
<div class="form-group col-md-2">
<label for="minValue">Min value</label>
<input name="minValue" type="text" value=0 class="form-control" id="minValue">
</div>
<div class="form-group col-md-2">
<label for="frameAmount">Number of frames</label>
<input name="frameAmount" type="text" value=10 placeholder="10" class="form-control" id="frameAmount">
</div>
<div class="form-group col-md-2">
<label for="translation">Translation</label>
<input name="translation" type="text" class="form-control" id="translation" placeholder="x">
</div>
<div class="form-group col-md-2">
<label class="text-center" for="linearInterpolation">Power of linear interpolation</label>
<input name="linearInterpolation" type="text" value=5 class="form-control" id="linearInterpolation">
</div>
<div class="form-group col-md-2">
<label for="omitted">list of omitted sensors</label>
<input name="omitted" type="text" class="form-control" id="omitted" placeholder="format eg. L4, L3, etc" value="">
</div>
</div>
<div class="d-flex flex-row justify-content-center">
<button id="form-submit" type="submit" class="text-center btn btn-primary">Submit</button>
</div>
</form>
You want to make yourself familiar with the FormData API. Use formData.entries() to access these:
$form.addEventListener('submit', (event) => {
event.preventDefault()
const formData = new FormData(event.target)
// log our form object
console.log(formData.entries().next().value)
event.target.reset()
})
<form id="$form">
<label for="parameter">Parameter</label>
<span class="asterisk_input"></span>
<select name="parameter" id="parameter" class="custom-select">
<option selected>Select a parameter</option>
<option value="air_temperature">Air humidity</option>
<option value="air_pressure">Air temperature</option>
<option value="air_humidity">Air pressure</option>
</select>
<button id="form-submit" type="submit" class="text-center btn btn-primary">Submit</button>
</form>

html required in form not working with issues in modal

I have a modal where i put my form inside. Now, my problem is, when i click the button of my onclick="regpatient()" button, the required will pop-up but when i look at it in console, the data was submited by a post because of my onlick function. How can i do this?
Here is my modal:
<div class="modal-body">
<form class="form-horizontal" id="frm_patientreg">
<div class="form-group">
<label class="control-label col-sm-3" for="pfname">First Name:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="pafname" name="pafname" placeholder="First name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pmname">Middle Name:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="pamname" name="pamname" placeholder="Middle name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="plname">Last Name:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="palname" name="palname" placeholder="Last name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="paddress">Address:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="paaddress" name="paaddress" placeholder="Address" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pcontact">Contact #:</label>
<div class="col-sm-7">
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' class="form-control" id="pacontact" name="pacontact" placeholder="Contact number" maxlength="11" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pbdate">Birthdate:</label>
<div class="col-sm-5">
<div class="input-group date" data-provide="datepicker">
<input type="text" class="form-control" id="pabdate" name="pabdate" placeholder="Birthdate" required>
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="page">Age:</label>
<div class="col-sm-4">
<input type="number" class="form-control" id="paage" name="paage" placeholder="Age" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pheight">Height:</label>
<div class="col-sm-4">
<input type="number" class="form-control" id="paheight" name="paheight" placeholder="Height (cm)" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pweight">Weight:</label>
<div class="col-sm-4">
<input type="number" class="form-control" id="paweight" name="paweight" placeholder="Weight (kg)" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="psex">Sex:</label>
<div class="col-sm-5">
<select class="form-control" id="psex" name="psex">
<option value="0">--- SELECT OPTION ---</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pmartiastat">Civil Status:</label>
<div class="col-sm-5">
<select class="form-control" id="pmartialstat" name="pmartialstat">
<option value="0">--- SELECT OPTION ---</option>
<option value="Single">Single</option>
<option value="Living common law">Living common law</option>
<option value="Married">Married</option>
<option value="Widowed">Widowed</option>
<option value="Separated">Separated</option>
<option value="Divorced">Divorced</option>
</select>
</div>
</div>
</div><!-- modal-body -->
<div class="modal-footer">
<button value="submit" onclick="regpatient()" class="btn btn-primary">Register Patient</button>
</form>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div><!-- modal-footer -->
</div><!-- modal-content -->
and here is my ajax where it fires when the button in footer of my modal is clicked:
function regpatient() {
var a = $('#psex').val();
var b = $('#pmartialstat').val();
if(a == "0" || b == "0") {
alert("Please select option");
}
else {
$.ajax({
url: siteurl+"sec_myclinic/addpatient",
type: "POST",
data: $('#frm_patientreg').serialize(),
dataType: "JSON",
success: function(data) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
}
If I understand your problem right you want to stop the button's default submit action and only use your onclick script. Try this:
onclick="regpatient(event)"
and
function regpatient(event) {
event.preventDefault();
...
Edit
The required fields are not getting validated by the onclick function. Some checks like this for the required values should help stop the ajax call.
if (!$('#pafname').val()) {
return alert('Please fill in all required fields.');
}
// ajax code here ...
Use this
<button value="button" onclick="regpatient()" class="btn btn-primary">Register Patient</button>
instead of this
<button value="submit" onclick="regpatient()" class="btn btn-primary">Register Patient</button>

Jquery Get iD and Value and display URL parameters

I used below HTML & JS script to get ID and value of each element inside the form.
But, i need to get all these value and like below and added to the URL on top when user submit the form to redirect booking engine.
Getting below output on console.log:
someaction?fromLocation=undefined&departureDate=undefined&tripType=undefined&returnDate=undefined
HTML:
<form method="POST" id="bookingForm" action="someaction">
<div class="col-lg-6">
<div class="form-group">
<label for="fromLocation">From:</label>
<select class="select form-control input-lg" id="fromLocation" form="fromLocation" name="fromLocation" required>
<option value="">From</option>
<option value="ADL">Adelaide</option>
<option value="DRW">Darwin</option>
<option value="MEL">Melbourne</option>
<option value="PER">Perth</option>
</select>
</div>
<div class="form-group">
<label for="departure">Departure Date:</label>
<input class="departureDate form-control" id="departureDate" type="text" placeholder="Departure Date" name="Departure Date" required>
</div>
<div class="form-group" id="tripType">
<label for="tripType">Trip Type:</label>
<div class="col-lg-12">
<div class="col-lg-2">
<input class="radio tripType" id="ReturnTrip" type="radio" name="tripType" value="Return" checked="">Return
</div>
<div class="col-lg-2">
<input class="radio tripType" id="SingleTrip" type="radio" name="tripType" value="One-way">One-way
</div>
<div class="col-lg-8"></div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="return">Return Date:</label>
<input class="returnDate form-control" type="text" id="returnDate" placeholder="Return Date" name="Return Date" required>
</div>
<div class="form-group" id="booking-btn--container">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</form>
JS:
var url = $("#bookingForm").attr("action") + "?";
var urlElements = [];
$("#bookingForm").find('.form-group').each(function(){
urlElements.push($(this).find('.form-control').attr("id") + "=" + $(this).find('.form-control').attr("value") || $(this).find('.form-control').attr("id") + "=" + $(this).find('.form-control').attr("value"));
});
urlElements = urlElements.join("&");
url += urlElements;
console.log(url);
Just fix your name attributes to match your IDs, and use .serialize():
$("form").on("submit", function(event) {
event.preventDefault();
var form = $(this);
var url = form.attr('action') + '?' + form.serialize();
console.log(url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" id="bookingForm" action="someaction">
<div class="col-lg-6">
<div class="form-group">
<label for="fromLocation">From:</label>
<select class="select form-control input-lg" id="fromLocation" name="fromLocation" required>
<option value="">From</option>
<option value="ADL">Adelaide</option>
<option value="DRW">Darwin</option>
<option value="MEL">Melbourne</option>
<option value="PER">Perth</option>
</select>
</div>
<div class="form-group">
<label for="departure">Departure Date:</label>
<input class="departureDate form-control" id="departureDate" type="text" placeholder="Departure Date" name="departureDate" required>
</div>
<div class="form-group" id="tripType">
<label for="tripType">Trip Type:</label>
<div class="col-lg-12">
<div class="col-lg-2">
<input class="radio tripType" id="ReturnTrip" type="radio" name="tripType" value="Return" checked="">Return
</div>
<div class="col-lg-2">
<input class="radio tripType" id="SingleTrip" type="radio" name="tripType" value="One-way">One-way
</div>
<div class="col-lg-8"></div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="return">Return Date:</label>
<input class="returnDate form-control" type="text" id="returnDate" placeholder="Return Date" name="returnDate" required>
</div>
<div class="form-group" id="booking-btn--container">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</form>
As a bonus, it will properly URL-encode your values.
Try like this
var $input = $(this).find('.form-control');
urlElements.push($input.attr("id") + "=" + $input.val());

Categories