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)
Related
im looking from a laravel or html example of fill out a form with several drop-down lists.
Here is my case. I have these inputs-text name_customer, phone_customer, email_customer,
I would like that when I select the customer, the form fields are filled with the customer information:(name_customer, phone_customer, email_customer from de database).
This what i have done so far.
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label>N° Commande</label>
<input
type="text"
class="form-control"
v-model="num_order"
name="num_order"
/>
</div>
<div class="form-group">
<label>customer</label>
<div class="form-check form-check-inline mr-1">
<input
onclick="document.getElementById('select_customer').disabled=!this.checked;
document.getElementById('text_name').disabled=this.checked;
document.getElementById('text_Tel').disabled=this.checked;
document.getElementById('text_Email').disabled=this.checked;
document.getElementById('text_address').disabled=this.checked"
class="form-check-input"
id="inline-checkbox1"
type="checkbox"
value="check1"
v-model="num_order"
name="num_order"
/>
<label
class="form-check-label"
for="inline-checkbox1"
>Existant</label
>
<div class="col-md-8">
<select
class="form-control form-control-sm"
id="select_customer"
name="select_customer"
disabled
onclick="document.getElementById('inline-checkbox1').disabled=!this.checked;"
v-model="customers_id"
#change="getcustomers()"
>
<option disabled value="0">
Choisir un customer
</option>
<option
v-for="customer in customers"
v-bind:key="customer.id"
v-bind:value="customer.id"
name="customers_id"
>
{{ customer.name_customer }}
</option>
</select>
</div>
</div>
<input
type="text"
class="form-control"
id="text_name"
placeholder="Name"
v-model="name_customer"
name="name_customer"
/>
</div>
<div class="form-group">
<label>Phone</label>
<input
type="text"
class="form-control"
id="text_Tel"
placeholder="Phone"
/>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Adresse du customer</label>
<textarea
rows="4"
class="form-control"
id="text_address"
placeholder="Address"
>
</textarea>
</div>
<div class="form-group">
<label>Email</label>
<input
type="text"
class="form-control"
id="text_Email"
placeholder="Email"
/>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Libellé</label>
<input type="text" class="form-control" />
</div>
<div class="row">
<div class="col-sm-6">
<label>Date Commande</label>
<input type="date" class="form-control" />
</div>
<div class="col-sm-6">
<label>Date Validation</label>
<input type="date" class="form-control" />
</div>
</div>
</div>
</div>
Thank you in advance.
Hi i found the solution to my problem.
<select
class="form-control form-control-sm"
id="select_customer"
name="select_customer"
v-model="customers_id"
#change="getcustomers()"
>
<option disabled value="0">
Choose a customer
</option>
<option
v-for="customer in customers"
v-bind:key="customer.id"
v-bind:value="{
id: customer.id,
name_customer: customer.name_customer,
phone_customer: customer.phone_customer}"
name="customers_id"
>
{{ customer.name_customer }}
</option>
</select>
<div class="form-group">
<label>Name</label>
<input
type="text"
class="form-control"
id="text_name"
v-model="customers_id.name_customer"
/>
</div>
<div class="form-group">
<label>Téléphone</label>
<input
type="text"
class="form-control"
id="text_Tel"
v-model="customers_id.phone_customer"
/>
</div>
var app = new Vue({
el: '#app',
data: {
customers_id: '',
customers: []
}
})
Here is how you can, after a selection from a drop-down list, fill in the input fields, the data obtained from the database.
You can also consult the vuejs documentation on this subject. https://v2.vuejs.org/v2/guide/forms.html#Select
I have form that is long and in some situations users might miss some of the required fields. If they scroll all the way to the Save button and click to send the form data they won't see error message. I'm wondering if there is a way to trigger on focus method that will take user to the first field in the form that is required or invalid. Here is example of my form:
var COMMON_FUNC = {};
$("#save").on("click", function() {
var frmObject = $(this).closest("form"),
frmDisabledFlds = frmObject.find(":input:disabled").prop("disabled", false),
frmData = frmObject.serialize();
frmDisabledFlds.prop("disabled", true);
if (COMMON_FUNC.verifyFields("new-record")) {
console.log('Send Form Data!');
}
});
COMMON_FUNC.verifyFields = function(containerID, includeInvisible) {
includeInvisible = includeInvisible || false;
let isValid = true;
const hdlMap = {
'valueMissing': "This field is required",
'patternMismatch': "This field is invalid",
'tooLong': "This field is too long",
'rangeOverflow': "This field is greater than allowed maximum",
'rangeUnderflow': "This field is less than allowed minimum",
'typeMismatch': "This field is mistyped"
};
const arrV = Object.keys(hdlMap);
$("#" + containerID).find("input,textarea,select").each(function() {
var curItem$ = $(this);
var errMsg = [];
var dispfld = curItem$.data("dispfld");
if (includeInvisible || curItem$.is(":visible")) {
if (curItem$[0].validity.valid) {
curItem$.removeClass("is-invalid");
return;
}
arrV.forEach(function(prop) {
if (curItem$[0].validity[prop]) {
if (prop === "patternMismatch" && dispfld) {
errMsg.push(dispfld);
} else {
errMsg.push(hdlMap[prop]);
}
}
});
if (errMsg.length) {
if (!curItem$.next().is(".invalid-feedback")) {
curItem$.after('<div class="invalid-feedback"></div>');
}
curItem$.addClass("is-invalid").next().text(errMsg.join(' and '));
isValid = false;
} else {
curItem$.removeClass("is-invalid");
}
}
});
return isValid;
};
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<div class="container">
<div class="card">
<div class="card-header">
<h4>New Record</h4>
</div>
<div class="card-body">
<form name="new-record" id="new-record" autocomplete="off">
<div class="form-group">
<label for="bldg_name">Building Name:</label>
<input class="form-control" type="text" name="bldg_name" id="bldg_name" value="" maxlength="500" placeholder="Enter the building name" required>
</div>
<div class="row">
<div class="col-12"><strong><u>Manager</u></strong></div>
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="salutation">Salutation:</label>
<select class="custom-select browser-default" name="salutation" id="salutation">
<option value="">--Select Salutation--</option>
<option value="1">Mrs</option>
<option value="2">Ms</option>
<option value="3">Miss</option>
<option value="4">Mr</option>
</select>
</div>
<div class="form-group col-6">
<label for="title">Business Title:</label>
<select class="custom-select browser-default" name="title" id="title">
<option value="">--Select Title--</option>
<option value="1">Region Manager</option>
<option value="2">State Manager</option>
<option value="3">Building Manager</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-6 required">
<label for="fname">First Name:</label>
<input class="form-control" type="text" name="fname" id="fname" value="" maxlength="20" placeholder="Enter First name" required>
</div>
<div class="form-group col-6 required">
<label for="lname">Last Name:</label>
<input class="form-control" type="text" name="lname" id="lname" value="" maxlength="30" placeholder="Enter Last name" required>
</div>
</div>
<div class="form-group required">
<label for="email">Email:</label>
<input class="form-control email" type="email" name="email" id="email" maxlength="50" placeholder="Enter Email address" required>
</div>
<div class="form-group row">
<div class="col-5 offset-2"><strong><u>Physical Address</u></strong></div>
<div class="col-5"><strong><u>Mailing Address</u></strong></div>
</div>
<div class="form-group row required">
<label for="address1" class="col-2 col-form-label">Address 1:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_address1" id="p_address1" value="" placeholder="Enter Physical Address 1" maxlength="40" required>
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_address1" id="m_address1" value="" placeholder="Enter Mailing Address 1" maxlength="40" required>
</div>
</div>
<div class="form-group row">
<label for="address2" class="col-2 col-form-label">Address 2:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_address2" id="p_address2" value="" placeholder="Enter Physical Address 2" maxlength="40">
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_address2" id="m_address2" value="" placeholder="Enter Mailing Address 2" maxlength="40">
</div>
</div>
<div class="form-group row">
<label for="address3" class="col-2 col-form-label">Address 3:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_address3" id="p_address3" value="" placeholder="Enter Physical Address 3" maxlength="40">
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_address3" id="m_address3" value="" placeholder="Enter Mailing Address 3" maxlength="40">
</div>
</div>
<div class="form-group row">
<label for="address4" class="col-2 col-form-label">Address 4:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_address4" id="p_address4" value="" placeholder="Enter Physical Address 4" maxlength="40">
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_address4" id="m_address4" value="" placeholder="Enter Mailing Address 4" maxlength="40">
</div>
</div>
<div class="form-group row required">
<label for="city" class="col-2 col-form-label">City:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_city" id="p_city" value="" placeholder="Enter City" maxlength="25" required>
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_city" id="m_city" value="" placeholder="Enter City" maxlength="25" required>
</div>
</div>
<div class="form-group row required">
<label for="state" class="col-2 col-form-label">State:</label>
<div class="col-5">
<select class="custom-select browser-default physical" name="p_state" id="p_state" required>
<option value="">--Select State--</option>
<option value="az">Arizona</option>
<option value="ia">Iowa</option>
<option value="mo">Missouri</option>
<option value="ny">New York</option>
<option value="va">Virginia</option>
</select>
</div>
<div class="col-5">
<select class="custom-select browser-default mailing" name="m_state" id="m_state" required>
<option value="">--Select State--</option>
<option value="az">Arizona</option>
<option value="ia">Iowa</option>
<option value="mo">Missouri</option>
<option value="ny">New York</option>
<option value="va">Virginia</option>
</select>
</div>
</div>
<div class="form-group row required">
<label for="zip" class="col-2 col-form-label">Zip:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_zip" id="p_zip" value="" pattern="(\d{5}([\-]\d{4})?)" data-dispfld="The required format is: xxxxx or xxxxx-xxxx" placeholder="Enter Zip Code, formatted: 99999 or 99999-9999" maxlength="10" required>
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_zip" id="m_zip" value="" pattern="(\d{5}([\-]\d{4})?)" data-dispfld="The required format is: xxxxx or xxxxx-xxxx" placeholder="Enter Zip Code, formatted: 99999 or 99999-9999" maxlength="10" required>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<button class="btn btn-outline-secondary" type="button" name="save" id="save">Save</button>
<button class="btn btn-outline-secondary" type="button" name="cancel" id="cancel">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
You can run this example and enter all information in the form but Building Name. Then you can click Save button, and you won;t be able to see the error message on the top. If anyone have suggestions how to handle this problem please let me know. I open to hear different solutions for this situations.
The DOM API has a "focus" function on elements that can do what you're looking for.
Push all your valid elements to an invalidInputs array, then you can choose the first element that is invalid and call .focus() on that element.
var COMMON_FUNC = {};
$("#save").on("click", function() {
var frmObject = $(this).closest("form"),
frmDisabledFlds = frmObject.find(":input:disabled").prop("disabled", false),
frmData = frmObject.serialize();
frmDisabledFlds.prop("disabled", true);
if (COMMON_FUNC.verifyFields("new-record")) {
console.log('Send Form Data!');
}
});
COMMON_FUNC.verifyFields = function(containerID, includeInvisible) {
includeInvisible = includeInvisible || false;
let isValid = true;
const hdlMap = {
'valueMissing': "This field is required",
'patternMismatch': "This field is invalid",
'tooLong': "This field is too long",
'rangeOverflow': "This field is greater than allowed maximum",
'rangeUnderflow': "This field is less than allowed minimum",
'typeMismatch': "This field is mistyped"
};
const arrV = Object.keys(hdlMap);
// Create an array for the invalid fields.
const invalidInputs = [];
$("#" + containerID).find("input,textarea,select").each(function() {
var curItem$ = $(this);
var errMsg = [];
var dispfld = curItem$.data("dispfld");
if (includeInvisible || curItem$.is(":visible")) {
if (curItem$[0].validity.valid) {
curItem$.removeClass("is-invalid");
return;
}
arrV.forEach(function(prop) {
if (curItem$[0].validity[prop]) {
if (prop === "patternMismatch" && dispfld) {
errMsg.push(dispfld);
} else {
errMsg.push(hdlMap[prop]);
}
}
});
if (errMsg.length) {
if (!curItem$.next().is(".invalid-feedback")) {
curItem$.after('<div class="invalid-feedback"></div>');
}
curItem$.addClass("is-invalid").next().text(errMsg.join(' and '));
isValid = false;
//Push the invalid inputs onto the invalidInputs array.
invalidInputs.push(curItem$);
} else {
curItem$.removeClass("is-invalid");
}
}
});
// Focus on the first element that is invalid.
invalidInputs[0].focus();
return isValid;
};
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<div class="container">
<div class="card">
<div class="card-header">
<h4>New Record</h4>
</div>
<div class="card-body">
<form name="new-record" id="new-record" autocomplete="off">
<div class="form-group">
<label for="bldg_name">Building Name:</label>
<input class="form-control" type="text" name="bldg_name" id="bldg_name" value="" maxlength="500" placeholder="Enter the building name" required>
</div>
<div class="row">
<div class="col-12"><strong><u>Manager</u></strong></div>
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="salutation">Salutation:</label>
<select class="custom-select browser-default" name="salutation" id="salutation">
<option value="">--Select Salutation--</option>
<option value="1">Mrs</option>
<option value="2">Ms</option>
<option value="3">Miss</option>
<option value="4">Mr</option>
</select>
</div>
<div class="form-group col-6">
<label for="title">Business Title:</label>
<select class="custom-select browser-default" name="title" id="title">
<option value="">--Select Title--</option>
<option value="1">Region Manager</option>
<option value="2">State Manager</option>
<option value="3">Building Manager</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-6 required">
<label for="fname">First Name:</label>
<input class="form-control" type="text" name="fname" id="fname" value="" maxlength="20" placeholder="Enter First name" required>
</div>
<div class="form-group col-6 required">
<label for="lname">Last Name:</label>
<input class="form-control" type="text" name="lname" id="lname" value="" maxlength="30" placeholder="Enter Last name" required>
</div>
</div>
<div class="form-group required">
<label for="email">Email:</label>
<input class="form-control email" type="email" name="email" id="email" maxlength="50" placeholder="Enter Email address" required>
</div>
<div class="form-group row">
<div class="col-5 offset-2"><strong><u>Physical Address</u></strong></div>
<div class="col-5"><strong><u>Mailing Address</u></strong></div>
</div>
<div class="form-group row required">
<label for="address1" class="col-2 col-form-label">Address 1:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_address1" id="p_address1" value="" placeholder="Enter Physical Address 1" maxlength="40" required>
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_address1" id="m_address1" value="" placeholder="Enter Mailing Address 1" maxlength="40" required>
</div>
</div>
<div class="form-group row">
<label for="address2" class="col-2 col-form-label">Address 2:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_address2" id="p_address2" value="" placeholder="Enter Physical Address 2" maxlength="40">
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_address2" id="m_address2" value="" placeholder="Enter Mailing Address 2" maxlength="40">
</div>
</div>
<div class="form-group row">
<label for="address3" class="col-2 col-form-label">Address 3:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_address3" id="p_address3" value="" placeholder="Enter Physical Address 3" maxlength="40">
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_address3" id="m_address3" value="" placeholder="Enter Mailing Address 3" maxlength="40">
</div>
</div>
<div class="form-group row">
<label for="address4" class="col-2 col-form-label">Address 4:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_address4" id="p_address4" value="" placeholder="Enter Physical Address 4" maxlength="40">
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_address4" id="m_address4" value="" placeholder="Enter Mailing Address 4" maxlength="40">
</div>
</div>
<div class="form-group row required">
<label for="city" class="col-2 col-form-label">City:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_city" id="p_city" value="" placeholder="Enter City" maxlength="25" required>
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_city" id="m_city" value="" placeholder="Enter City" maxlength="25" required>
</div>
</div>
<div class="form-group row required">
<label for="state" class="col-2 col-form-label">State:</label>
<div class="col-5">
<select class="custom-select browser-default physical" name="p_state" id="p_state" required>
<option value="">--Select State--</option>
<option value="az">Arizona</option>
<option value="ia">Iowa</option>
<option value="mo">Missouri</option>
<option value="ny">New York</option>
<option value="va">Virginia</option>
</select>
</div>
<div class="col-5">
<select class="custom-select browser-default mailing" name="m_state" id="m_state" required>
<option value="">--Select State--</option>
<option value="az">Arizona</option>
<option value="ia">Iowa</option>
<option value="mo">Missouri</option>
<option value="ny">New York</option>
<option value="va">Virginia</option>
</select>
</div>
</div>
<div class="form-group row required">
<label for="zip" class="col-2 col-form-label">Zip:</label>
<div class="col-5">
<input class="form-control physical" type="text" name="p_zip" id="p_zip" value="" pattern="(\d{5}([\-]\d{4})?)" data-dispfld="The required format is: xxxxx or xxxxx-xxxx" placeholder="Enter Zip Code, formatted: 99999 or 99999-9999" maxlength="10" required>
</div>
<div class="col-5">
<input class="form-control mailing" type="text" name="m_zip" id="m_zip" value="" pattern="(\d{5}([\-]\d{4})?)" data-dispfld="The required format is: xxxxx or xxxxx-xxxx" placeholder="Enter Zip Code, formatted: 99999 or 99999-9999" maxlength="10" required>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<button class="btn btn-outline-secondary" type="button" name="save" id="save">Save</button>
<button class="btn btn-outline-secondary" type="button" name="cancel" id="cancel">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
You can try something simple like this (untested but should work):
document.getElementsByClassName('is-invalid')[0].scrollIntoView({ behavior: 'smooth' });
This looks for error class is-invalid then does a smooth scroll to the first one found
Add this code after the validation, if there are errors found.
On the button you need to bind the event using a function like the below one:
function submitForm(event) {
for (var i = 0; i < event.elements.length; i++) {
if (event.elements[i].required) {
if (event.elements[i].value == "") {
event.elements[i].focus();
break;
}
}
}
}
I hope this could help ~Rdaksh
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 am trying to implement on click add a new input field.So, There are 2 buttons to add and remove input box after clicking on add button it should add a set of the input box and on clicking remove button it should remove the particular input box. But on Clicking "add" it only adds 1 input field and refreshes the whole page and the form data of that page is showing in the search bar but on the other side "remove" button works fine. Both the functions are right I guess but I don't understand what is wrong? What do I do? I don't want add button to refresh the page and showing data in the search bar. And it must add many no of input boxes after clicking on it. What needs to be done here. please help!!
Here is my code:
index.php
<form method="post">
<div class="form-group " >
<input type="text" placeholder="Campaign Name" class="form-control c-square c-theme input-lg" name="camp_name"> </div>
<div class="row col-md-12">
<div class="form-group col-md-6">Start Date
<input type="date" placeholder="start date" class="form-control c-square c-theme input-lg" name="start_date">
</div>
<div class="form-group col-md-6">End Date
<input type="date" placeholder="end date" class="form-control c-square c-theme input-lg" name="end_date"> </div>
</div>
<div class="row col-md-12">
<div class="form-group">
<label for="inputPassword3" class="col-md-8 control-label">Select Store</label>
<div class="col-md-6 c-margin-b-20">
<select class="form-control c-square c-border-2px c-theme" multiple="multiple" name="store">
<option value="1">All Stores</option>
<option value="2">Phoenix Mall</option>
<option value="3">1MG Mall</option>
<option value="4">Orion Mall</option>
</select>
</div>
</div>
</div>
<div class="row col-md-12" ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<label for="inputPassword3" class="col-md-1 control-label">Elements</label>
<div class="form-group col-md-3 ">
<input type="text" placeholder="Campaign Name" ng-model="choice.name" class="form-control c-square c-theme input-lg" name="ele">
</div>
<label for="inputPassword3" class="col-md-1 control-label">Quantity</label>
<div class="form-group col-md-3" >
<select class="form-control c-square c-border-2px c-theme" name="store">
<option value="1">All Stores</option>
<option value="2">Phoenix Mall</option>
<option value="3">1MG Mall</option>
<option value="4">Orion Mall</option>
</select>
</div>
<button class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square"
ng-click="addNewChoice()" >
add
</button>
<button ng-show="$last" ng-click="removeChoice()"
class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" >
Remove
</button>
</fieldset>
</div>
</div>
</div>
<div class="form-group">
<input type="text" placeholder="Description" class="form-control c-square c-theme input-lg" name="description">
</div>
<input class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" value="Submit" type="submit">
</form>
angular script
<script type="text/javascript">
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
</script>
The default type of a button element is submit. That is the reason your form gets submitted. In order to avoid this behaviour you can set the type to button as in the below code.
References w3.org
Reference Html Standard
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form method="post">
<div class="form-group " >
<input type="text" placeholder="Campaign Name" class="form-control c-square c-theme input-lg" name="camp_name"> </div>
<div class="row col-md-12">
<div class="form-group col-md-6">Start Date
<input type="date" placeholder="start date" class="form-control c-square c-theme input-lg" name="start_date">
</div>
<div class="form-group col-md-6">End Date
<input type="date" placeholder="end date" class="form-control c-square c-theme input-lg" name="end_date"> </div>
</div>
<div class="row col-md-12">
<div class="form-group">
<label for="inputPassword3" class="col-md-8 control-label">Select Store</label>
<div class="col-md-6 c-margin-b-20">
<select class="form-control c-square c-border-2px c-theme" multiple="multiple" name="store">
<option value="1">All Stores</option>
<option value="2">Phoenix Mall</option>
<option value="3">1MG Mall</option>
<option value="4">Orion Mall</option>
</select>
</div>
</div>
</div>
<div class="row col-md-12" ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<label for="inputPassword3" class="col-md-1 control-label">Elements</label>
<div class="form-group col-md-3 ">
<input type="text" placeholder="Campaign Name" ng-model="choice.name" class="form-control c-square c-theme input-lg" name="ele">
</div>
<label for="inputPassword3" class="col-md-1 control-label">Quantity</label>
<div class="form-group col-md-3" >
<select class="form-control c-square c-border-2px c-theme" name="store">
<option value="1">All Stores</option>
<option value="2">Phoenix Mall</option>
<option value="3">1MG Mall</option>
<option value="4">Orion Mall</option>
</select>
</div>
<button type="button" class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square"
ng-click="addNewChoice()" >
add
</button>
<button type="button" ng-show="$last" ng-click="removeChoice()"
class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" >
Remove
</button>
</fieldset>
</div>
</div>
</div>
<div class="form-group">
<input type="text" placeholder="Description" class="form-control c-square c-theme input-lg" name="description">
</div>
<input class="btn c-theme-btn c-btn-uppercase btn-lg c-btn-bold c-btn-square" value="Submit" type="submit">
</form>
Hope this helps :)
I wrote SignupForm function to validate, but this is giving an error that function is not defined.Please check the code snippet.I am using jquery validate function.your help will be appreciated.Thank you.
$(function() {
var $signupForm = $('#SignupForm');
$signupForm.validate({
errorElement: 'em'
});
$signupForm.formToWizard({
submitButton: 'SaveAccount',
nextBtnClass: 'btn btn-primary next',
prevBtnClass: 'btn btn-default prev',
buttonTag: 'button',
validateBeforeNext: function(form, step) {
var stepIsValid = true;
var validator = form.validate();
$(':input', step).each(function(index) {
var xy = validator.element(this);
stepIsValid = stepIsValid && (typeof xy == 'undefined' || xy);
});
return stepIsValid;
},
progress: function(i, count) {
$('#progress-complete').width('' + (i / count * 100) + '%');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<script src="https://raw.githubusercontent.com/artoodetoo/formToWizard/master/jquery.formtowizard.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<form id="SignupForm" action="">
<fieldset>
<legend>Account information</legend>
<div class="form-group">
<label for="Name">Name</label>
<input id="Name" type="text" class="form-control" required />
</div>
<div class="form-group">
<label for="Email">Email</label>
<input id="Email" type="email" class="form-control" required />
</div>
<div class="form-group">
<label for="Password">Password</label>
<input id="Password" type="password" class="form-control" />
</div>
</fieldset>
<fieldset>
<legend>Company information</legend>
<div class="form-group">
<label for="CompanyName">Company Name</label>
<input id="CompanyName" type="text" class="form-control" required />
</div>
<div class="form-group">
<label for="Website">Website</label>
<input id="Website" type="text" class="form-control" />
</div>
<div class="form-group">
<label for="CompanyEmail">CompanyEmail</label>
<input id="CompanyEmail" type="text" class="form-control" />
</div>
</fieldset>
<fieldset class="form-horizontal" role="form">
<legend>Billing information</legend>
<div class="form-group">
<label for="NameOnCard" class="col-sm-2 control-label">Name on Card</label>
<div class="col-sm-10"><input id="NameOnCard" type="text" class="form-control" /></div>
</div>
<div class="form-group">
<label for="CardNumber" class="col-sm-2 control-label">Card Number</label>
<div class="col-sm-10"><input id="CardNumber" type="text" class="form-control" /></div>
</div>
<div class="form-group">
<label for="CreditcardMonth" class="col-sm-2 control-label">Expiration</label>
<div class="col-sm-10">
<div class="row">
<div class="col-xs-3">
<select id="CreditcardMonth" class="form-control col-sm-2">
<option value="1">1</option>
<option value="12">12</option>
</select>
</div>
<div class="col-xs-3">
<select id="CreditcardYear" class="form-control">
<option value="2009">2009</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="Address1" class="col-sm-2 control-label">Address 1</label>
<div class="col-sm-10"><input id="Address1" type="text" class="form-control" /></div>
</div>
<div class="form-group">
<label for="Address2" class="col-sm-2 control-label">Address 2</label>
<div class="col-sm-10"><input id="Address2" type="text" class="form-control" /></div>
</div>
<div class="form-group">
<label for="Zip" class="col-sm-2 control-label">ZIP</label>
<div class="col-sm-4"><input id="Zip" type="text" class="form-control" /></div>
<label for="Country" class="col-sm-2 control-label">Country</label>
<div class="col-sm-4"><select id="Country" class="form-control">
<option value="CA">Canada</option>
<option value="US">United States of America</option>
<option value="GB">United Kingdom (Great Britain)</option>
<option value="AU">Australia</option>
<option value="YE">Yemen</option>
<option value="ZR">Zaire</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
</div>
</fieldset>
<p>
<button id="SaveAccount" class="btn btn-primary submit">Submit form</button>
</p>
</form>
Seems you did not added jQuery library in your code. http://code.jquery.com/jquery-3.1.1.min.js
<script src="//code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<script>
$( function() {
var $signupForm = $( '#SignupForm' );
$signupForm.validate({errorElement: 'em'});
});
</script>
<form id="SignupForm" action="">
<fieldset>
<legend>Account information</legend>
<div class="form-group">
<label for="Name">Name</label>
<input id="Name" type="text" class="form-control" required />
</div>
<div class="form-group">
<label for="Email">Email</label>
<input id="Email" type="email" class="form-control" required />
</div>
<div class="form-group">
<label for="Password">Password</label>
<input id="Password" type="password" class="form-control" />
</div>
</fieldset>
<fieldset>
<legend>Company information</legend>
<div class="form-group">
<label for="CompanyName">Company Name</label>
<input id="CompanyName" type="text" class="form-control" required />
</div>
<div class="form-group">
<label for="Website">Website</label>
<input id="Website" type="text" class="form-control" />
</div>
<div class="form-group">
<label for="CompanyEmail">CompanyEmail</label>
<input id="CompanyEmail" type="text" class="form-control" />
</div>
</fieldset>
<fieldset class="form-horizontal" role="form">
<legend>Billing information</legend>
<div class="form-group">
<label for="NameOnCard" class="col-sm-2 control-label">Name on Card</label>
<div class="col-sm-10"><input id="NameOnCard" type="text" class="form-control" /></div>
</div>
<div class="form-group">
<label for="CardNumber" class="col-sm-2 control-label">Card Number</label>
<div class="col-sm-10"><input id="CardNumber" type="text" class="form-control" /></div>
</div>
<div class="form-group">
<label for="CreditcardMonth" class="col-sm-2 control-label">Expiration</label>
<div class="col-sm-10"><div class="row">
<div class="col-xs-3">
<select id="CreditcardMonth" class="form-control col-sm-2">
<option value="1">1</option>
<option value="12">12</option>
</select>
</div>
<div class="col-xs-3">
<select id="CreditcardYear" class="form-control">
<option value="2009">2009</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
</select>
</div>
</div></div>
</div>
<div class="form-group">
<label for="Address1" class="col-sm-2 control-label">Address 1</label>
<div class="col-sm-10"><input id="Address1" type="text" class="form-control" /></div>
</div>
<div class="form-group">
<label for="Address2" class="col-sm-2 control-label">Address 2</label>
<div class="col-sm-10"><input id="Address2" type="text" class="form-control" /></div>
</div>
<div class="form-group">
<label for="Zip" class="col-sm-2 control-label">ZIP</label>
<div class="col-sm-4"><input id="Zip" type="text" class="form-control" /></div>
<label for="Country" class="col-sm-2 control-label">Country</label>
<div class="col-sm-4"><select id="Country" class="form-control">
<option value="CA">Canada</option>
<option value="US">United States of America</option>
<option value="GB">United Kingdom (Great Britain)</option>
<option value="AU">Australia</option>
<option value="YE">Yemen</option>
<option value="ZR">Zaire</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
</div>
</fieldset>
<p>
<button id="SaveAccount" class="btn btn-primary submit">Submit form</button>
</p>
</form>
MG