Validation not working.I am using bootstrap Modal to show the users input form and has a confirmation button.I have submitted the first form which calls the validation and modal at the same time.
<form class="form-phone" name="frm" method="post" enctype="multipart/form-data" id="add_name" action="">
<input type="text" class="form-control" id="ex_model" name="ex_model" required>
<input type="text" class="form-control" id="ex_serial" name="ex_serial" required>
<button style="width:100% ; margin-top:15px; border-radius:0; font-weight:bold;" type="button" id="subBtn" class="btn btn-success" data-toggle="modal" data-target="#myModal" >GET OFFER</button>
</form>
Here is the script
<script >
$(document).ready(function(){
$('#subBtn').click(function() {
$("#add_name").validate({
rules: {
ex_model: {
required: true,
minlength: 8
},
ex_serial: "required"
},
messages: {
ex_model: {
required: "Please enter modaldata",
minlength: "Your data must be at least 8 characters"
},
ex_serial: "Please enter some data"
}
});
});
});
</script>
You don't need to validate this form on submit button click event instead of you can validate that form on $(document).ready(function(){}) itself
$(function(){
$("#add_name").validate({
rules: {
ex_model: {
required: true,
minlength: 8
},
ex_serial: "required"
},
messages: {
ex_model: {
required: "Please enter modaldata",
minlength: "Your data must be at least 8 characters"
},
ex_serial: "Please enter some data"
}
})
$("#subBtn").on("click", function(){
if($("#add_name").valid()){
//alert("success");
$("#myModal").modal("show");
} else {
//alert("Values are not entered");
//whatever you want to do when values are not entered
}
return false;
});
})
<link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<form class="form-phone" name="frm" method="post" enctype="multipart/form-data" id="add_name" action="">
<input type="text" class="form-control" id="ex_model" name="ex_model" required>
<input type="text" class="form-control" id="ex_serial" name="ex_serial" required>
<button style="width:100% ; margin-top:15px; border-radius:0; font-weight:bold;" type="button" id="subBtn" class="btn btn-success" >GET OFFER</button>
</form>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Yes you can validate form using below code
$("subBtn").on('click', function() {
$("#add_name").valid();
});
Related
I am working in one inventory project I use bootsrap modal for inserting and updating records the problem that I am facing is that when I am editing the record the jquery validation only applied on first row not on any other row can any one help me in this matter.
index page is like below
<tbody>
#foreach ($suppliers as $key => $supplier)
<tr class="odd">
<td class="sorting_1 dtr-control">{{ $key + 1 }}</td>
<td>{{ $supplier->name }}</td>
<td>{{ $supplier->mobile_no }}</td>
<td>{{ $supplier->email }}</td>
<td>{{ $supplier->address }}</td>
<td>
<a href="#edit{{ $supplier->id }}" data-bs-toggle="modal" class="fas fa-edit" title="Edit Data" style=" margin-right:20px">
</a>
#include('backend.supplier.editSupplier')
</td>
</tr>
#endforeach
</tbody>
Modal is like below
<div class="modal fade editModal" id="edit{{ $supplier->id }}" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Supplier</h5>
<button type="button" class=" btn btn-danger btn btn-sm close" data-bs-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="editForm" method="POST" action="{{ route('supplier.update', $supplier->id) }}"
class="needs-validation" novalidate>
#csrf
#method('PUT')
<div class="modal-body">
<!-- name -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="name" placeholder="Supplier Name"
id="name" name="name1" value="{{ $supplier->name }}">
</div>
</div>
<!-- mobile number -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="text" autocomplete="mobile_no"
placeholder="Mobile Number" id="mobile_no" name="mobile_no1"
value="{{ $supplier->mobile_no }}">
</div>
</div>
<!-- email -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="email_address" placeholder="Email" id="email_address"
name="email_address1" value="{{ $supplier->email }}">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="address" placeholder="Address"
id="address" name="address1" value="{{ $supplier->address }}">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"
onclick="resetForm()">No</button>
<button type="submit" class="btn btn-primary">Add Supplier</button>
</div>
</form>
</div>
</div>
</div>
Jquery code is like below
<script type="text/javascript">
$(document).ready(function() {
$('#editForm').validate({
rules: {
name1: {
required: true,
},
mobile_no1: {
required: true,
},
address1: {
required: true,
},
email_address1: {
required: true,
},
},
messages: {
name1: {
required: 'Please Enter Supplier Name',
},
mobile_no1: {
required: 'Please Enter Supplier mobile number',
},
address1: {
required: 'Please Enter Supplier address',
},
email_address1: {
required: 'Please Enter Supplier email',
},
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
},
});
});
function resetForm() {
$("#editForm").trigger("reset");
var validator = $("#editForm").validate();
validator.resetForm();
}
</script>
This is a VERY verbose example but here I take a rendered table and remove the form from that. This avoids duplication of the id's on the form and also gives you smaller HTML and the ability to use the same form over in every row and on and "add" action.
I then trigger the edit with the edit link/button; it saves by submit of the form but you could alter that to post the data using ajax or something also.
I did not venture into the "add" but you could put a button on the screen for that also; stick the id or whatever you need in the "action" to save the NEW item in that part.
$(function() {
$('#editForm').validate({
rules: {
name1: {
required: true,
},
mobile_no1: {
required: true,
},
address1: {
required: true,
},
email_address1: {
required: true,
}
},
messages: {
name1: {
required: 'Please Enter Supplier Name',
},
mobile_no1: {
required: 'Please Enter Supplier mobile number',
},
address1: {
required: 'Please Enter Supplier address',
},
email_address1: {
required: 'Please Enter Supplier email',
}
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
$('#my-great-suppliers').on('click', '.edit-link', function(event) {
//event.preventDefault().preventPropagation();
console.log('set up edit');
const trow = $(this).closest('.supplier-row');
console.log("Row:", trow.index(), trow.length);
const modal = $('#edit-modal-container').find('.edit-modal-child');
const modalForm = modal.find('#editForm');
const rowEdits = trow.find('.edit-me');
let supplierid = $(this).data("supplierid");
let name = rowEdits.filter('[data-suppliername]').data("suppliername");
let email = rowEdits.filter('[data-email]').data("email");
let mobile = rowEdits.filter('[data-mobile]').data("mobile");
let address = rowEdits.filter('[data-address]').data("address");
console.log(supplierid, name, trow.length);
modalForm.find('#name').val(name);
modalForm.find('#email_address').val(email);
modalForm.find('#address').val(address);
modalForm.find('#mobile_no').val(mobile);
let actionV = modalForm.attr("action");
console.log(actionV);
// update the form action with the id
modalForm.attr("action", actionV + supplierid);
// modal.show();
});
$('.submit-button').on('click', function(event) {
event.preventDefault();
const modalForm = $('#editForm');
console.log("trying to save");
// now do what you need to validate
if (modalForm.valid()) {
// add your extra logic here to execute only when element is valid
console.log('It is valid');
let savedata = {
name: modalForm.find('#name').val(),
email: modalForm.find('#email_address').val(),
address: modalForm.find('#address').val(),
mobile: modalForm.find('#mobile_no').val()
};
console.log("Saving:", savedata, 'To:', modalForm.attr("action"));
//now do what you want to save the form
// since we updated the action when edit started we have the id in there
// modalForm.submit()
}
});
});
function resetForm() {
$("#editForm").trigger("reset");
let validator = $("#editForm").validate();
validator.resetForm();
}
.edit-link {
margin-right: 20px;
}
.edit-modal-container {}
.cheers {
border: solid 1px green;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js" integrity="sha512-rstIgDs0xPgmG6RX1Aba4KV5cWJbAMcvRCVmglpam9SoHZiUCyQVDdH2LPlxoHtrv17XWblE/V/PP+Tr04hbtA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<table id="my-great-suppliers" class="my-great-suppliers-container">
<tbody>
<tr class="supplier-row odd">
<td class="sorting_1 dtr-control">$key1</td>
<td class='edit-me' data-suppliername="Dirt supplier">Dirt supplier</td>
<td class="edit-me" data-mobile="123-123-1234">123-123-1234</td>
<td class="edit-me" data-email="happydays#example.com">happydays#example.com</td>
<td class="edit-me" data-address="1234 Main St">1234 Main St</td>
<td>
<a href="#" data-supplierid="supplier-1" data-bs-toggle="modal" class="edit-link fas fa-edit" title="Edit Data" data-bs-target="#supplier-modal">
</a>
</td>
</tr>
<tr class="supplier-row odd">
<td class="sorting_1 dtr-control">$key2</td>
<td class='edit-me' data-suppliername="Rock supplier">Rock supplier</td>
<td class='edit-me' data-mobile="321-123-4321">321-123-4321</td>
<td class='edit-me' data-email="biggerrocks#example.com">biggerrocks#example.com</td>
<td class='edit-me' data-address="12 Granite Lane">12 Granite Lane</td>
<td>
<a href="#" data-supplierid="supplier-2" data-bs-toggle="modal" class="edit-link fas fa-edit" data-bs-target="#supplier-modal" title="Edit Data">
</a>
</td>
</tr>
</tbody>
</table>
<div id="edit-modal-container" class="edit-modal-container">
<div id='supplier-modal' class="edit-modal-child modal fade editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Supplier</h5>
<button type="button" class="btn btn-danger btn btn-sm close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="editForm" method="POST" action="/route/supplierupdate/" class="needs-validation" novalidate>
<div class="modal-body">
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="name" placeholder="Supplier Name" id="name" name="name1" value="">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="text" autocomplete="mobile_no" placeholder="Mobile Number" id="mobile_no" name="mobile_no1" value="">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="email_address" placeholder="Email" id="email_address" name="email_address1" value="">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="address" placeholder="Address" id="address" name="address1" value="">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="resetForm()">No</button>
<button type="submit" class="submit-button btn btn-primary">Add Supplier</button>
</div>
</form>
</div>
</div>
</div>
</div>
if you try to inspect the modal on each row. the input will have the same name eg. name1, mobile_no1, etc.
Jquery will validate the first input element with that name.
You can either move the modal and Jquery function each with their own unique id inside foreach. may use $supplier->id
Or
Im guessing the modal already inside the foreach since it have the unique id. Update eqch input to include the unique id(name="mobile_no1<?php $supplier-id ?>") Then, update the jquery function to accept id identifier($supplier->id) so it can fetch the unique input element
I'm validating fields inside modal popup,for single field it is working but if more than one field are appended at a time then validation does not takes place on those fields. Here we can see we add new field by adding add field button but those newly field did'nt get validated.
$(function() {
$("#newModalForm").validate();
$('.form-control').each(function() {
required($(this))
});
$(document).on('click', '#add_field', function(e) {
$('#dynamic_div').html("<div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 1:</label> <inputname=sfs type=text class=form-control></div> <div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 2:</label><input name=ssf type=text class=form-control></div>");
required($(this))
});
function required(el) {
el.rules("add", {
required: true,
messages: {
required: "This field is required",
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMyModal">Open Modal</button>
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form role="form" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="pName" name="pName" placeholder="Enter a p name"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" name="action" placeholder="Enter and action">
</div>
</div>
<div class="col-md-9" id="dynamic_div">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" id="add_field" class="btn btn-default">Add Field</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
You need call .each() on the dynamically added elements as well.
Dynamically added elements are not in DOM onload so ideally you need to do wrap .each() in a function when you add more fields to your modal just call that function again to check for empty inputs
To handle submit and store data we can .submit on your modal form. Get all the data via .serialize method and send all your form data to the backend file via ajax request.
Run Snippet below to see it working.
$(function() {
//Validate Data
var validate = $("#newModalForm").validate()
checkInput()
//Add dynamic inputs
$(document).on('click', '#add_field', function(e) {
$('#dynamic_div').html("<div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 1:</label> <input name=sfs type=text class=form-control></div> <div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 2:</label><input name=ssf type=text class=form-control></div>");
//Required Dynamic Input
checkInput()
});
//Validate all inputs
function checkInput() {
$('.form-control').each(function() {
required($(this))
});
}
//Required field message
function required(el) {
el.rules("add", {
required: true,
messages: {
required: "This field is required",
}
});
}
//Submit form modal
$('#newModalForm').on('submit', function(e) {
//Prevent default submit behaviour
e.preventDefault()
//Store all the form modal form data
var data = $(this).serialize()
//Check all fieild have data
if (validate.errorList.length == 0) {
alert('All fields have value - Form will submit now')
//Request to backend
$.ajax({
url: 'your_url',
type: 'POST',
data: data,
success: function(response) {
//do something on success
},
error: function(xhr) {
//Handle errors
}
});
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMyModal">Open Modal</button>
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form role="form" method="post" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="pName" name="pName" placeholder="Enter a p name" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" name="action" placeholder="Enter and action">
</div>
</div>
<div class="col-md-9" id="dynamic_div">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" id="add_field" class="btn btn-default">Add Field</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
I'm doing some testing with AJAX form submissions and I keep getting ReferenceError: submit_ajax is not defined from the code below. However, you can see that it IS defined.
<script type="javascript">
function submit_ajax(){
data = {'email':$('#email2').val(),'password':$('#pwd2').val()}
$.ajax({
url: 'ajax_testing.php',
data: data,
success: function() {
//AJAX success
$('#success_fail').html('success!');
window.setTimeout(function() { $('#success_fail').hide(); }, 3000);
$('#myModal2').hide();
},
error: function() {
//Ajax failure
$('#success_fail').html('failed!');
window.setTimeout(function() { $('#success_fail').hide(); }, 3000);
$('#myModal2').hide();
}
});
}
</script>
<div>
<div id="success_fail"></div>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" id="button_for_modal2" data-toggle="modal" data-target="#myModal2">Form Submitted via AJAX and No Parent Refresh</button>
<!-- Modal -->
<div class="modal fade" id="myModal2" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Title of Form</h4>
</div>
<div class="modal-body">
<h2>Vertical (basic) form</h2>
<!--<form action="<?PHP echo $_SERVER['PHP_SELF']; ?>" method="post">*******************************AJAX*********************************-->
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email2" placeholder="Enter email (ajax)" name="email2">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd2" placeholder="Enter password (ajax)" name="pwd2">
</div>
<button onclick="submit_ajax()" class="btn btn-default">Submit</button>
<!--</form>-->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
I've tried running the function directly in the console and I get the same thing.
Any idea about what's going wrong here?
Instead of using <script type="javascript"> use <script type="text/javascript"> which is valid type for JS code.
change your script tag, either dont include type or set it as type="text/javascript"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function submit_ajax(){
alert('submit_ajax working')
data = {'email':$('#email2').val(),'password':$('#pwd2').val()}
$.ajax({
url: 'ajax_testing.php',
data: data,
success: function() {
//AJAX success
$('#success_fail').html('success!');
window.setTimeout(function() { $('#success_fail').hide(); }, 3000);
$('#myModal2').hide();
},
error: function() {
//Ajax failure
$('#success_fail').html('failed!');
window.setTimeout(function() { $('#success_fail').hide(); }, 3000);
$('#myModal2').hide();
}
});
}
</script>
<button onclick="submit_ajax()" class="btn btn-default">Submit</button>
So I am new to bootstrap and so far I've got everything working the way I want. I have created a contact form which uses the Modal Form and sends the email via PHP using the Mail function.
I have created a script to do the validation on the form. If the validation passes I want the email to be sent out.
Currently when the user submits the form that is blank the validation isn't working and the email is getting sent.
Please keep in mind I'm am new to working with bootstrap.
HTML
<div id="ContactUs" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Contact Us</h4>
<p><b>XXXX</b><br>
Company Phone: XXXXX
</p>
</div>
<form id="contactForm" method="post" action="scripts/email.php">
<div class="modal-body">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Please enter your full name here.">
<label for="name">Email</label>
<input type="text" name="email" id="email" class="form-control" placeholder="Please enter your email address here.">
<label for="name">Subject</label>
<input type="text" name="subject" id="subject" class="form-control" placeholder="Please enter your subject here.">
<label for="message">Message</label>
<textarea name="message" class="form-control" placeholder="Please enter your message here."></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
Script
$(document).ready(function()
{
$validator = $("#contactForm").validate({
errorClass:'error',
validClass:'success',
errorElement:'span',
highlight: function (element, errorClass, validClass) {
$(element).parents("div[class='clearfix']").addClass(errorClass).removeClass(validClass);
},
unhighlight: function (element, errorClass, validClass) {
$(element).parents(".error").removeClass(errorClass).addClass(validClass);
},
rules: {
name: {
required: true,
minlength: 2
},
subject: {
required: true,
minlength: 10
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 10
}
},
messages: {
name: {
required: '<span class="help-inline">Your name is required</span>',
minlength: jQuery.format('<span class="help-inline">2 chars</span>')
},
subject: {
required: '<span class="help-inline">A Subject is required.
</span>',
minlength:jQuery.format('<span class="help-inline">10 characters</span>')
},
email: {
required: '<span class="help-inline">Email.</span>',
email: '<span class="help-inline">Ex : name#exemple.com</span>'
},
message: {
required: '<span class="help-block">Message</span>',
minlength: jQuery.format('<span class="help-block">10 chars</span>')
}
},
submitHandler: function(form)
{
$('form').submit(function() {
if ($validator.numberOfInvalids() > 0)
{
$('#submit').modal('hide');
} else
{
$('#submit').modal('show');
}
});
}
});
});
On each input field add 'required'. Simple way to ensure each field has data
<form id="contactForm" method="post" action="scripts/email.php">
<div class="modal-body">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Please enter your full name here." required />
<label for="name">Email</label>
<input type="text" name="email" id="email" class="form-control" placeholder="Please enter your email address here." required />
<label for="name">Subject</label>
<input type="text" name="subject" id="subject" class="form-control" placeholder="Please enter your subject here." required />
<label for="message">Message</label>
<textarea name="message" class="form-control" placeholder="Please enter your message here." required /></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Did you already include jquery and validation library?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
pass your form to your button with attribute
<button type="submit" class="btn btn-primary" form="ContactUs">Submit</button>
you should put your form id inside that
I use jquery validation plugin to do validation in a bootstrap modal form, when i send the form ,the jquery validation plugin is not working also the form cannot send out.
bootstrap modal form
<div class="modal fade" id="form-content" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close"
data-dismiss="modal" aria-hidden="true">
×
</button>
<h3>send message</h3>
</div>
<div class="modal-body">
<form class="contact">
<fieldset>
<div class="modal-body">
<ul class="nav nav-list">
<div class="form-group">
<label for="topic" class="control-label ">topic:</label>
<input class="form-control" type="text" name="topic">
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="ruser" class="control-label ">ruser: </label>
<input class="form-control" type="text" name="ruser">
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="content" class="control-label ">content:</label>
<textarea class="form-control" name="content" rows="3"></textarea>
<span class="help-block"></span>
</div>
</ul>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-success" type="submit">send</button>
close
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<button class="btn btn-success btn-lg" data-toggle="modal"
data-target="#form-content">
send message
</button>
javascript
$(document).ready(function(){
$('form').validate({
rules: {
topic: {
required: true
},
ruser: {
required: true
},
content: {
required: true
}
},
messages : {
topic: {
required: 'enter topic'
},
ruser: {
required: 'enter ruser'
},
content: {
required: 'enter content'
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
submitHandler: function (form) {
alert('valid form submission'); // for demo
$.ajax({
type: "POST",
url: "process.php",
data: $('form.contact').serialize(),
success: function(msg){
if(msg=='no'){
alert(msg);
}
else if(msg=='ok!'){
alert(msg);
location.reload()
}
},
error: function(){
alert("failure");
}
});
return false;
}
});
});
How can i fix the problem?
The jsfiddle
The problem is the submit button is not a descendant of the form you are trying to submit.
One possible solution is to write a click handler for the button, and call the form submit from there like
<div class="modal-footer">
<button class="btn btn-success" id="submitcontact">send</button>
close
</div>
then
$('#submitcontact').click(function(){
$('form.contact').submit();
})
Demo: Fiddle
Firstly, As your Jquery code has one error:
On line no. 40 :- } replace with },
And solution is to call a function on onclick event of your button. No need to remove type="submit" as it's removed in Arun's answer.
Inside $(document).ready(function() write below function:
$('#sendForm').click(function(){
$('form.contact').submit();
})
And it will work. WOKRING DEMO