Get inputs values from a form : JavaScript - javascript

I have a dynamic form Like this in image :
How can I get each adult separately in variable like this :
[["Mr.","aa","bb"],["Mrs","cc","dd"],["Dr.","ee","ff"]]
I submit the form in Ajax, so I need this data serialized. I defined class add_pax_adult_x and x is the number of each adult. I have this code below. every this is ok and I can return the data but I need to return this format as I mentioned.
$(document).on('submit','#passenger_details_form',function(event){
var toatalAdults = [];
var adultsPax = [];
for(var x=1; x<=$('#adults').val(); x++){
var inputs = $(".add_pax_adult_"+x);
for(var i = 0; i < inputs.length; i++){
adultsPax.push($(inputs[i]).val())
}
toatalAdults.push(adultsPax);
}
alert(toatalAdults);
});
<div class="col-sm-5 adultsDiv" style="padding-left: 0">
<select id="adults" required="" class="form-control adults" name="no_of_adults">
<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select>
</div>
<div class="col-sm-12" >
<div class="row passengerDetailsAdults">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">Adult 1</label>
<select id="pax_title" name="pax_title[]" class="form-control pax_title add_pax_adult_1">
<option value="Mr." selected="">Mr.</option>
<option value="Mrs">Mrs</option>
<option value="Ms.">Ms.</option>
<option value="Miss">Miss</option>
<option value="Dr.">Dr.</option>
<option value="Prof.">Prof.</option>
<option value="Sir">Sir</option>
<option value="Lady">Lady</option>
<option value="">--</option>
</select>
</div>
<div class="form-group">
<label class="control-label">First Name *</label>
<input type="text" value="" maxlength="100" class="form-control adult_fname add_pax_adult_1" name="adult_fname[]" id="adult_fname" required>
</div>
<div class="form-group">
<label class="control-label">Last Name *</label>
<input type="text" value="" maxlength="100" class="form-control adult_lname add_pax_adult_1" name="adult_lname[]" id="adult_lname" required>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">Adult 2</label>
<select id="pax_title" name="pax_title[]" class="form-control pax_title add_pax_adult_2">
<option value="Mr." selected="">Mr.</option>
<option value="Mrs">Mrs</option>
<option value="Ms.">Ms.</option>
<option value="Miss">Miss</option>
<option value="Dr.">Dr.</option>
<option value="Prof.">Prof.</option>
<option value="Sir">Sir</option>
<option value="Lady">Lady</option>
<option value="">--</option>
</select>
</div>
<div class="form-group">
<label class="control-label">First Name *</label>
<input type="text" value="" maxlength="100" class="form-control adult_fname add_pax_adult_2" name="adult_fname[]" id="adult_fname" required>
</div>
<div class="form-group">
<label class="control-label">Last Name *</label>
<input type="text" value="" maxlength="100" class="form-control adult_lname add_pax_adult_2" name="adult_lname[]" id="adult_lname" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">Adult 3</label>
<select id="pax_title" name="pax_title[]" class="form-control pax_title add_pax_adult_3">
<option value="Mr." selected="">Mr.</option>
<option value="Mrs">Mrs</option>
<option value="Ms.">Ms.</option>
<option value="Miss">Miss</option>
<option value="Dr.">Dr.</option>
<option value="Prof.">Prof.</option>
<option value="Sir">Sir</option>
<option value="Lady">Lady</option>
<option value="">--</option>
</select>
</div>
<div class="form-group">
<label class="control-label">First Name *</label>
<input type="text" value="" maxlength="100" class="form-control adult_fname add_pax_adult_3" name="adult_fname[]" id="adult_fname" required>
</div>
<div class="form-group">
<label class="control-label">Last Name *</label>
<input type="text" value="" maxlength="100" class="form-control adult_lname add_pax_adult_3" name="adult_lname[]" id="adult_lname" required>

Try below code
<?php if(isset($_GET['task']) && $_GET['task'] == 'send'){
$request = [];
foreach($_POST['pax_title'] as $k=>$pax_title){
$request []=[$pax_title,$_POST['adult_fname'][$k],$_POST['adult_lname'][$k]];
}
print_r($request);exit(); } ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>Passenger reservation</h1>
<b>Adult :: </b><select class="form-control" id="number_adult">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<hr>
<form action="index.php" method="post" id="passenger_details_form" class="form-inline">
<div id="form_data">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Adult 1</label>
<select id="pax_title" name="pax_title[]" class="form-control">
<option value="Mr." selected="">Mr.</option>
<option value="Mrs">Mrs</option>
<option value="Ms.">Ms.</option>
<option value="Miss">Miss</option>
<option value="Dr.">Dr.</option>
<option value="Prof.">Prof.</option>
<option value="Sir">Sir</option>
<option value="Lady">Lady</option>
<option value="">--</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">First Name *</label>
<input type="text" maxlength="100" class="form-control" name="adult_fname[]" id="adult_fname" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Last Name *</label>
<input type="text" maxlength="100" class="form-control" name="adult_lname[]" id="adult_lname" required>
</div>
</div>
</div>
</div>
<hr>
<button type="submit" class="btn btn-primary">Save</button>
</form>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="">
$(document).ready(function(){
$('#number_adult').on('change',function(){
for(var i=0;i<$(this).val();i++){
var num = parseInt($('#form_data').children().length)+1;
$('#form_data').append('<div class="row"><div class="col-md-4"><div class="form-group"><label class="control-label">Adult '+num+'</label> <select id="pax_title" name="pax_title[]" class="form-control"><option value="Mr." selected="">Mr.</option><option value="Mrs">Mrs</option><option value="Ms.">Ms.</option><option value="Miss">Miss</option><option value="Dr.">Dr.</option><option value="Prof.">Prof.</option><option value="Sir">Sir</option><option value="Lady">Lady</option><option value="">--</option></select></div></div><div class="col-md-4"><div class="form-group"><label class="control-label">First Name *</label> <input type="text" maxlength="100" class="form-control" name="adult_fname[]" id="adult_fname" required></div></div><div class="col-md-4"><div class="form-group"><label class="control-label">Last Name *</label> <input type="text" maxlength="100" class="form-control" name="adult_lname[]" id="adult_lname" required></div></div></div>');
}
});
$(document).on('submit','#passenger_details_form',function(event){
var serialized=$("#passenger_details_form").serialize();
$.ajax({
method: "POST",
url: "index.php?task=send",
data: serialized
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
event.preventDefault();
return false;
});
});
</script>

You say you need the data serialized, well you're in luck, just use the <form Element>.serialize() method.
i.e. You have this form
<form id="myForm">
...
</form>
In your script, just do this
var serialized=$("$myForm").serialize();
Voila, it is now serialized in standard AJAX notation.

Related

empty form fields when I change value of select

i have a form contains select category_id which allows hide and show inputs title and name and select type, i want when i change category id value all other fields must be empty.
$(document).on('change', '#category_id', function() {
$("#divt > input,#divtn > input,#divty > input").val('');
var stateID = $(this).val();
//alert(stateID);
if (stateID == '1') {
$("#divt").hide();
$("#divn").hide();
$("#divty").show();
}else if(stateID == '2'){
$("#divt").show();
$("#divn").show();
$("#divty").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<form id="myform">
<div class="form-group">
<label>Categories <span class="text-hightlight">*</span></label>
<select class="form-control" name="category_id" id="category_id">
<option>select</option>
<option value="1">title</option>
<option value="2">name</option>
</select>
</div>
<div class="form-group" id="divt">
<label>title <span class="text-hightlight">*</span></label>
<input type="text" name="title" class="form-control"/>
</div>
<div class="form-group" id="divn">
<label>name <span class="text-hightlight">*</span></label>
<input type="text" name="name" id="name" class="form-control"/>
</div>
<div class="form-group" id="divty">
<label>type <span class="text-hightlight">*</span></label>
<select class="form-control" name="type">
<option></option>
<option value="1">type a</option>
<option value="2">type b</option>
</select>
</div>
</form>
</div>
To reset the select field you need this code
$("#divty").find('option:first-child').prop('selected', true)
.end().trigger('chosen:updated');
Here is the working snippet:
$(document).on('change', '#category_id', function() {
$("#divt > input,#divtn > input,#divty > input").val('');
var stateID = $(this).val();
//alert(stateID);
if (stateID == '1') {
$("#divty").find('option:first-child').prop('selected', true)
.end().trigger('chosen:updated');
$("#divt").hide();
$("#divn").hide();
$("#divty").show();
}else if(stateID == '2'){
$("#divt > input").val('');
$("#divn > input").val('');
$("#divt").show();
$("#divn").show();
$("#divty").hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<form id="myform">
<div class="form-group">
<label>Categories <span class="text-hightlight">*</span></label>
<select class="form-control" name="category_id" id="category_id">
<option>select</option>
<option value="1">title</option>
<option value="2">name</option>
</select>
</div>
<div class="form-group" id="divt">
<label>title <span class="text-hightlight">*</span></label>
<input type="text" name="title" class="form-control"/>
</div>
<div class="form-group" id="divn">
<label>name <span class="text-hightlight">*</span></label>
<input type="text" name="name" id="name" class="form-control"/>
</div>
<div class="form-group" id="divty">
<label>type <span class="text-hightlight">*</span></label>
<select class="form-control" name="type">
<option></option>
<option value="1">type a</option>
<option value="2">type b</option>
</select>
</div>
</form>
</div>
If you're trying to empty value of the textboxes, I guess the selector is wrong on line 2
try
$("input.form-control").val('');
or $("#myform input.form-control").val('')

How can I do it : When checked radio button change input required?

I need help. I have 3 radio button 1. Credit Cart 2. Cargo Payment
3. Bank Payment
So I want when checked id ="credit" (Credit Cart) : Credit cart information inputs to be required with JS.
When the selected Radio button becomes credit card, the card information is opened. No card payment is required when others are selected. Therefore, it will be mandatory to enter information only when cart is selected.
$('input[name="cname"]').change(function() {
if ($("#kart").is(':checked')) {
$('#cname').add.attr('required');
$('#cnumber').add.attr('required');
$('#cmonth').add.attr('required');
$('#cyear').add.attr('required');
$('#ccvc').add.attr('required');
} else {
$('#cname').removeAttr('required');
$('#cnumber').removeAttr('required');
$('#cmonth').removeAttr('required');
$('#cyear').removeAttr('required');
$('#ccvc').removeAttr('required');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-block my-3">
<div class="custom-control custom-radio" id="kart">
<input id="credit" name="paymentType" checked type="radio" value="Kredi Kartı" class="custom-control-input">
<label class="custom-control-label" for="credit">Paiement par carte Kreadi</label>
</div>
<div class="custom-control custom-radio" id="kapida">
<input id="cargo" name="paymentType" type="radio" value="Kapıda Ödeme" class="custom-control-input">
<label class="custom-control-label" for="cargo">Payer à la Porte</label>
</div>
<div class="custom-control custom-radio" id="havale">
<input id="bank" name="paymentType" type="radio" value="Banka Havale" class="custom-control-input">
<label class="custom-control-label" for="bank">Paiement par Virement Bancaire</label>
</div>
</div>
<div class="row" id="kartodeme">
<div class="col-sm-6">
<div class="row">
<div class="col-md-12 mb-3">
<label for="">Nom et Prénom Sur la Carte</label>
<input type="text" name="cname" class="form-control" id="cname" placeholder="Prénom / Nom de Famille">
</div>
</div>
<div class="row">
<div class="col-md-12 mb-3">
<label for="">Numéro de Carte</label>
<input type="text" name="cnumber" min="16" max="16" class="form-control" id="cnumber" placeholder="XXXX-XXXX-XXXX-XXXX">
</div>
</div>
<div class="row">
<div class="col-md-12 mb-1">
<label for="">Date d'expiration</label>
</div>
<div class="col-md-4 mb-3">
<label for="">Lune</label>
<select name="cmonth" id="cmonth" class="form-control">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<div class="col-md-4 mb-3">
<label for="">An</label>
<select name="cyear" id="cyear" class="form-control">
<option value="20">2020</option>
<option value="21">2021</option>
<option value="22">2022</option>
<option value="23">2023</option>
<option value="24">2024</option>
<option value="25">2025</option>
<option value="26">2026</option>
<option value="27">2027</option>
<option value="28">2028</option>
<option value="29">2029</option>
</select>
</div>
<div class="col-md-4 mb-3">
<label for="">CVC</label>
<input type="text" name="ccvc" class="form-control" id="ccvc" placeholder="123">
</div>
</div>
</div>
<div class="col-sm-6">
</div>
</div>
Your question isn't so clear, but if you are trying to enforce validation when #credit radio is checked you can approach it as follows:
Store a variable, let's call it const isValidationRequired = false;
Have event listeners on all radio inputs. Let's say you add a class radios-wrapper on the parent div, so select the following:
`
function handleRadioClick(e) {
const targetId = e.target.id;
if (targetId == "credit") {
isValidationRequired = true;
}
}
const radiosWrapper = document.querySelector('.radios-wrapper');
const radios = radiosWrapper.querySelectorAll('input[type='radio']');
radios.forEach(radio => radio.addEventListener('click', handleRadioClick))
Several things
You want to run on click of the radio
You want to test credit and not kart
To validate a select, it needs an empty <option value="">Month</option>
const cc = () => {
const checked = $("#credit").is(':checked');
['cnumber', 'cmonth', 'cyear', 'ccvc', 'cname'].forEach(ele => {
$ele = $("#" + ele);
if ($ele.length > 0) { // test if the element exists
if (checked) $ele.attr("required", true);
else $ele.removeAttr("required");
}
})
};
$('[name=paymentType]').on('click', cc)
cc(); // on load
// extra code to generate the years from current year
const year = +String(new Date().getFullYear()).slice(2);
let curMonth = new Date().getMonth()+1;
$("#cyear")[0].options.length=1; // remove all but one
for (let i=year, n = year+9; i<=n;i++) {
$("#cyear").append($('<option/>',{text:i,value:i}));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="d-block my-3">
<div class="custom-control custom-radio" id="kart">
<input id="credit" name="paymentType" checked type="radio" value="Kredi Kartı" class="custom-control-input">
<label class="custom-control-label" for="credit">Paiement par carte Kreadi</label>
</div>
<div class="custom-control custom-radio" id="kapida">
<input id="cargo" name="paymentType" type="radio" value="Kapıda Ödeme" class="custom-control-input">
<label class="custom-control-label" for="cargo">Payer à la Porte</label>
</div>
<div class="custom-control custom-radio" id="havale">
<input id="bank" name="paymentType" type="radio" value="Banka Havale" class="custom-control-input">
<label class="custom-control-label" for="bank">Paiement par Virement Bancaire</label>
</div>
</div>
<div class="row" id="kartodeme">
<div class="col-sm-6">
<div class="row">
<div class="col-md-12 mb-3">
<label for="">Nom et Prénom Sur la Carte</label>
<input type="text" name="cname" class="form-control" id="cname" placeholder="Prénom / Nom de Famille">
</div>
</div>
<div class="row">
<div class="col-md-12 mb-3">
<label for="">Numéro de Carte</label>
<input type="text" name="cnumber" min="16" max="16" class="form-control" id="cnumber" placeholder="XXXX-XXXX-XXXX-XXXX">
</div>
</div>
<div class="row">
<div class="col-md-12 mb-1">
<label>Date d'expiration <input type="date" /></label>
</div>
<div class="col-md-4 mb-3">
<select name="cmonth" id="cmonth" class="form-control">
<option value="">Lune</option>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<div class="col-md-4 mb-3">
<select name="cyear" id="cyear" class="form-control">
<option value="">An</option>
<option value="20">2020</option>
<option value="21">2021</option>
<option value="22">2022</option>
<option value="23">2023</option>
<option value="24">2024</option>
<option value="25">2025</option>
<option value="26">2026</option>
<option value="27">2027</option>
<option value="28">2028</option>
<option value="29">2029</option>
</select>
</div>
<div class="col-md-4 mb-3">
<label for="ccvc">CVC</label>
<input type="text" name="ccvc" class="form-control" id="ccvc" placeholder="123">
</div>
</div>
</div>
<div class="col-sm-6">
<input type="submit">
</div>
</div>

How to focus on required or invalid field?

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

form loading despite of using e.preventDefault();

I am making an ajax form but the problem is that form is loading despite using e.preventDefault(). I have googled a lot and found the most answer but still not working.
$(document).ready(function() {
$("#upload").on('submit', function(e) {
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="upload" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label" for="input-email">Product Name</label>
<input type="text" name="ProductNamees" value="" placeholder="Enter Product Name" id="Product" class="form-control">
</div>
<div class="form-group">
<label class="control-label" for="input-email">Category</label>
<select name="category" name="category" value="" id="category" class="form-control">
<option value="0">Category</option>
<option value="1">Flower Bouquet (Buke)</option>
<option value="2">Flower Garland (Har)</option>
<option value="3">Stage Decoration</option>
<option value="4">Bed Decoration</option>
<option value="5">Car Decoration</option>
<option value="6">Home Decoration</option>
<option value="7">Palna Decoration</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="input-email">file upload</label>
<input type="file" name="files" value="" placeholder="" id="file" class="form-control">
</div>
<div class="form-group">
<label class="control-label" for="input-email">price</label>
<input type="text" name="price" value="" placeholder="Enter price" id="price" class="form-control">
</div>
<input type="submit" id="uploadsdfkf" name="upload" value="upload" class="btn check btn-primary">
</form>

Validate function of jquery is not working

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

Categories