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.
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>
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>
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"
what i want is that when i click on button "find reservation", the form submit should not refresh the page. Instead it should enable some fields in find reservation form underneath. But I am not able to achieve that. I am using bootstrap.
Here is my html part:-
<div class="container">
<div class="jumbotron checkInGuest">
<h3 class="h3Heading">Request for following information from guest</h3>
<form class="form-horizontal" id="checkInForm">
<div class="form-group">
<label for="reservationId" class="col-md-4">Reservation Id</label>
<div class="col-md-8">
<input type="text" class="form-control" id="reservationId" name="reservationId" required>
</div>
</div>
<div class="form-group">
<label for="dlNum" class="col-md-4">Driver License #</label>
<div class="col-md-8">
<input type="number" class="form-control" id="dlNum" min="0" name="dlNum" required>
</div>
</div>
<div class="form-group">
<div class="col-md-2">
<button type="submit" class="btn btn-success" id="findResButton">Find Reservation</button>
</div>
</div>
</form>
<!-- Form when info is found. Initially all fields are disabled-->
<div class="clear clearWithBorder"></div>
<h3 class="h3Heading">Information Found</h3>
<form class="form-horizontal">
<div class="form-group">
<label for="resId" class="col-md-3">Reservation Id</label>
<div class="col-md-3">
<input type="text" class="form-control" id="resId" name="resId" disabled>
</div>
<label for="dlNumReadOnly" class="col-md-3">Driver License #</label>
<div class="col-md-3">
<input type="number" class="form-control" id="dlNumReadOnly" min="0" name="dlNumReadOnly" disabled>
</div>
</div>
<div class="form-group">
<label for="guestFullName" class="col-md-3">Guest Full Name</label>
<div class="col-md-3">
<input type="text" class="form-control" id="guestFullName" name="guestFullName" disabled>
</div>
<label for="email" class="col-md-3">Email</label>
<div class="col-md-3">
<input type="email" class="form-control" id="email" name="email" disabled>
</div>
</div>
<div class="form-group">
<label for="numRooms" class="col-md-3">Rooms Booked</label>
<div class="col-md-3">
<input type="number" class="form-control readable" id="numRooms" name="numRooms" disabled>
</div>
<label for="roomType" class="col-md-1">Room Type</label>
<div class=" col-md-2">
<label for="smoking">
<input type="radio" name="roomType" id="smoking" class="roomType readable" disabled> Smoking
</label>
</div>
<div class=" col-md-3">
<label for="nonSmoking">
<input type="radio" name="roomType" id="nonSmoking" class="roomType readable" disabled>Non-Smoking
</label>
</div>
</div>
<div class="form-group">
<label for="discount" class="col-md-3">Discount</label>
<div class="col-md-3">
<select class="form-control readable" id="discount" disabled>
<option selected>0%</option>
<option>10%</option>
<option>20%</option>
<option>30%</option>
</select>
</div>
<label for="checkInDate" class="col-md-3">CheckIn Date</label>
<div class="col-md-3">
<input type="date" class="form-control readable" id="checkInDate" name="checkInDate" disabled>
</div>
</div>
<div class="form-group">
<label for="checkOutDate" class="col-md-3">CheckOut Date</label>
<div class="col-md-9">
<input type="date" class="form-control readable" id="checkOutDate" name="checkInDate" disabled>
</div>
</div>
<div class="form-group">
<div class="col-md-2">
<button type="button" class="btn btn-success" id="roomOrdButton">Confirm Room Order</button>
</div>
</div>
</form>
<div class="clear clearWithBorder"></div>
<h3 class="h3Heading">Final Room Order</h3>
<form class="form-horizontal">
<div class="form-group">
<label for="perInEachRoom" class="col-md-12">Number of people in each room</label>
<div class="col-md-8 " id="perInEachRoom">
</div>
<div class="form-group">
<div class="col-md-2">
<button type="button" class="btn btn-success" id="checkInButton">Check In</button>
</div>
</div>
</div>
</form>
</div>
</div>
And this is jquery part:-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$("#checkInForm").validator();
$("#findResButton").click(function(e){
e.preventDefault();
$(".readable").prop("disabled",false);
});
$("#roomOrdButton").click(function(){
var numberOfRooms=$("#numRooms").val();
var counter=0;
var container=$('<div/>');
$(".readable").prop("disabled",true);
for(counter=1;counter<=numberOfRooms;counter++){
container.append('<label for="room">Room '+counter+'</label><input type="number" class="form-control readable" name="checkInDate" />');
}
$("#perInEachRoom").html(container);
});
$("#checkInButton").click(function(){
$("#perInEachRoom").html("");
});
</script>
You need to put your code in a document.ready() function, so:
$(document).ready(function() {
$("#checkInForm").validator();
$("#findResButton").click(function(e){
e.preventDefault();
$(".readable").prop("disabled",false);
});
$("#roomOrdButton").click(function(){
var numberOfRooms=$("#numRooms").val();
var counter=0;
var container=$('<div/>');
$(".readable").prop("disabled",true);
for(counter=1;counter<=numberOfRooms;counter++){
container.append('<label for="room">Room '+counter+'</label><input type="number" class="form-control readable" name="checkInDate" />');
}
$("#perInEachRoom").html(container);
});
$("#checkInButton").click(function(){
$("#perInEachRoom").html("");
});
});
You should also have a look at this question: Form is submitted when I click on the button in form. How to avoid this?
Long story short, you should use
<button type="button"...
not
<button type="submit"...
Actually, all I did is:-
$("#checkInForm").submit(function(e)
{
e.preventDefault();
});
And that solved it. I didnt have to change button type or anything. Basically, in future when I will make AJAX calls I will have the code underneath preventDefault statement.