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

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>

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)

jQuery/PHP dynamic form submission

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.

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>

Form validation with parsley js. Alphanumeric and password confirmation

Currently validating a multistep form using parsley.js. All other required attributes works fine and validate properly. I just need help extending the form validation to ensure that the values for both password and confirm password fields match
$(function () {
var $sections = $('.form-section');
function navigateTo(index) {
// Mark the current section with the class 'current'
$sections
.removeClass('current')
.eq(index)
.addClass('current');
// Show only the navigation buttons that make sense for the current section:
$('.form-navigation .previous').toggle(index > 0);
var atTheEnd = index >= $sections.length - 1;
$('.form-navigation .next').toggle(!atTheEnd);
$('.form-navigation [type=submit]').toggle(atTheEnd);
}
function curIndex() {
// Return the current index by looking at which section has the class 'current'
return $sections.index($sections.filter('.current'));
}
// Previous button is easy, just go back
$('.form-navigation .previous').click(function() {
navigateTo(curIndex() - 1);
});
// Next button goes forward iff current block validates
$('.form-navigation .next').click(function() {
if ($('#individualForm').parsley().validate({group: 'block-' + curIndex()}))
navigateTo(curIndex() + 1);
});
// Prepare sections by setting the `data-parsley-group` attribute to 'block-0', 'block-1', etc.
$sections.each(function(index, section) {
$(section).find(':input').attr('data-parsley-group', 'block-' + index);
});
navigateTo(0); // Start at the beginning
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.5.1/parsley.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="individualForm" action="" class="indivform" method="post">
<div id="individualForm1" class="form-section">
</div>
<div class="regForm">
<div class="form-group formGroup">
<label for="usertype"> Tell us who you are </label>
<select class="form-control allForms" name="usertype" id="usertype">
<option selected>Student</option>
<option>Intern</option>
<option>National Service</option>
<option>Entry-Level Employee</option>
<option>Mid-level Manager</option>
<option>Senior-Level Manager</option>
<option>Executive</option>
<option>Foreign Expert</option>
</select>
</div>
</div>
<div class="form-group formGroup">
<label for="email"> Email Address</label>
<input type="email" name="email" id="email" class="form-control allForms" required placeholder="Enter your email address">
</div>
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="form-group formGroup">
<label for="password"> Password </label>
<input type="password" name="password" id="password" minlength="6" class="form-control allForms" required placeholder="Enter password">
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="form-group formGroup">
<label for="password_confirmation"> Confirm Password </label>
<input type="password" name="password_confirmation" minlength="6" id="password_confirmation" class="form-control allForms" required placeholder="Re-enter password">
</div>
</div>
</div>
</div>
<div id="individualForm2" class="form-section">
<div class="text-center stepImages">
<img src="img/step-2.png" alt="step one image">
</div>
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="form-group formGroup">
<label for="firstname"> First Name</label>
<input type="text" name="firstname" id="firstname" class="form-control allForms" required placeholder="Enter first name">
</div>
<div class="form-group formGroup">
<label for="country">Your location</label>
<select class="form-control allForms" name="country" id="country" data-placeholder="Select country">
<option value="0">Getting your location...</option>
#if(isset($countries))
#foreach($countries as $country)
<option value="{{ $country->id }}" title="{{ $country->country_code }}">{{ $country->name }}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="form-group formGroup">
<label for="lastname">Contact Last Name</label>
<input type="text" name="lastname" id="lastname" class="form-control allForms" required placeholder="Enter last name">
</div>
<div class="genderBox2 form-group formGroup">
<br>
<div class="radio-inline">
<label>
<input type="radio" name="gender" value="Male" checked="" >
Male
</label>
</div>
<div class="radio-inline">
<label>
<input type="radio" name="gender" value="Female">
Female
</label>
</div>
</div>
</div>
</div>
<div class="form-group formGroup">
{{--<div class="pi-col-sm-3">--}}
<div class="form-group">
<input name="dialcode" id="dialcode" class="form-control" placeholder="Dial Code" type="text">
</div>
{{--</div>--}}
<div class="form-group">
<input name="dialcode" id="dialcode" class="form-control" placeholder="Dial Code" required type="text">
</div>
<label for="individual_phone_number"> Phone Number</label>
<input type="text" name="phone" id="individual_phone_number" class="form-control allForms" required data-parsley-type="digits" placeholder="Enter your phone number">
</div>
</div>
<div class="modal-footer modalFooter form-navigation">
<button class="previous btn btn-success pull-left" id="newUserSubmitBtn" type="button"> Prev < </button>
<button class="next btn btn-success pull-right" id="newUserSubmitBtn" type="button"> Next > </button>
<button class="btn btn-default pull-right" id="individualSubmitBtn" type="submit"> Finish </button>
<span class="clearfix"></span>
</div>
</form>
and for both to be alphanumeric.
Should be easy using data-parsley-equalto and data-parsley-type="alphanum"

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