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
Related
Simple bootstrap 5 (with validation) contact form with Ajax call gets executed only when i hit submit button second time and it also save data twice. this form is inside modal form and this behavior happened when i added Ajax function to code..
I am not sure what is stopping form submission successfully after validation, form gets submitted only when i hit submit button second time and it save same data twice.
based on references i used e.stopImmediatePropagation(); but there behavior didnt change
<!-- Modal -->
<div class="modal-form modal fade" id="modal-form" data-bs-backdrop="static" tabindex="-1"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Register you interest</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="form-body">
<div class="row">
<div class="form-holder">
<div class="form-content">
<div class="form-items">
<p>Fill in the details below, we will get back to you!</p>
<form id="contactForm" class="requires-validation" action="sendemail.php" method="POST" novalidate >
<div class="col-md-12 mb-3">
<input class="form-control" type="text" name="name" placeholder="Full Name" required>
<div class="valid-feedback">Full Name field is valid!</div>
<div class="invalid-feedback">Full Name field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<input id="phone" type="tel" name="phone" class="form-control"
onkeypress="return isNumber(event)" required>
<div class="valid-feedback phoneinvalid" id="phoneinvalid"></div>
<div class="invalid-feedback">Phone field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<textarea class="form-control" name="message" id="message" placeholder="Your Message"></textarea>
</div>
<div class="form-button mt-3">
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-success-msg"></div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
JS Part
(function () {
'use strict'
const forms = document.querySelectorAll('.requires-validation')
Array.from(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
console.log("form.checkValidity() "+form.checkValidity());
if (!form.checkValidity()) {
// form.classList.remove('was-validated')
//event.preventDefault();
//event.stopPropagation();
e.stopImmediatePropagation();
form.classList.add('was-validated')
return;
}
else
{
console.log("This line should execute only if Form is validated");
AjaxCallSaveData();
form.classList.add('was-validated')
}
}, false)
})
})();
function AjaxCallSaveData()
{
console.log(" I am AjaxCall Function");
$("form").submit(function (event) {
var formData = {
name: $("#name").val(),
phone: $("#phone").val(),
message: $("#message").val(),
};
$.ajax({
type: "POST",
url: "SaveData.php",
data: formData,
dataType: "json",
encode: true
}).done(function (data) {
console.log(data);
if (!data.success) {
console.log("alert alert-warning");
} else {
console.log("alert alert-success");
$(".form-success-msg").add("display","block");
$("form").html(
'<div class="alert alert-success">' + data.message + "</div>"
);
}
});
event.preventDefault();
});
}
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();
});
i have problem with validate submit button.
so here my code:
var handleValidation = function() {
var form = $('#form-date');
var error = $('.alert-danger', form);
var success = $('.alert-success', form);
form.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "", // validate all fields including form hidden input
rules: {
start: {
required: true,
date: true,
remote: {
url: "<?php echo site_url('activity/check_date')?>",
type: "post",
data: {
start: function(){ return $("#date").val(); }
}
}
},
end: {
required: true,
date: true,
remote: {
url: "<?php echo site_url('activity/check_end')?>",
type: "post",
data: {
end: function(){ return $("#end").val(); }
}
}
},
},
messages: {
start:
{
remote: 'Date already in use.'
},
end:
{
remote: 'Date already in use.'
},
},
invalidHandler: function (event, validator) { //display error alert on form submit
success.hide();
error.show();
App.scrollTo(error, -200);
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.form-group').addClass('has-error'); // set error class to the control group
},
unhighlight: function (element) { // revert the change done by hightlight
$(element)
.closest('.form-group').removeClass('has-error'); // set error class to the control group
},
success: function (label) {
label
.closest('.form-group').removeClass('has-error'); // set success class to the control group
},
submitHandler: function (form) {
success.show();
error.hide();
form[0].submit(); // submit the form
}
});
}
<form class="form-horizontal" id="form-date" role="form" method="post" action="<?php echo base_url(); ?>activity/add">
<div class="form-body">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
You have some form errors. Please check below.
</div>
<div class="alert alert-success display-hide">
<button class="close" data-close="alert"></button>
Your form validation is successful!
</div>
<input type="hidden" class="form-control" name="nik" value="<?php echo $this->session->userdata('nik')?>">
<div class="form-group">
<label class="col-sm-3 control-label">Start Date:<span
class="required">*</span> </label>
<div class="col-sm-7">
<div class="input-group date date-picker" data-date-format="yyyy-mm-dd">
<input type="text" class="form-control" readonly id="date" name="start" required>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">End Date:<span
class="required">*</span> </label>
<div class="col-sm-7">
<div class="input-group date date-picker" data-date-format="yyyy-mm-dd">
<input type="text" class="form-control" readonly id="end" name="end" required>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-5">
<button type="submit" class="btn green">
<i class="fa fa-pencil"></i> Create</button>
<button type="button" class="btn default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</form>
i have validate where data is empty show warning,but if data succesful.only show warning success and didn't redirect.in console error show
form[0].submit is not a function(…)
so where is wrong code.
how to resolve it?
Just change :
form[0].submit();
To
form.submit();
The form argument of submitHandler() is the dom element not a jQuery object and per plugin docs should be submitted using native submit
I have a modal as so
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="page-title">
Add Movie
<small>Note fields marked with <span style="color:red">*</span> are required</small>
</h2>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" id="NewMovie">
<div class="form-group">
<label class="control-label col-sm-4" for="prefix">
Title <span style="color:red">*</span>
</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="Title" name="Title" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="prefix">
Classification <span style="color:red">*</span>
</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="Classification" name="Classification" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="prefix">
Rating <span style="color:red">*</span>
</label>
<div class="col-sm-6">
<input id="Rating" name="Rating" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="5" data-slider-step="1" data-slider-value="0" /> <span id="rate" style="margin-left:5%">0 / 5</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="prefix">
Release Date <span style="color:red">*</span>
</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="ReleaseDate" name="ReleaseDate" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="prefix">
Cast <span style="color:red">*</span>
</label>
<div class="col-sm-5">
<input type="text" class="form-control col-sm-5" id="Cast" />
</div>
<div class="col-sm-1">
<button type="button" id="btnNewCast" class="btn btn-default">+</button>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="prefix"></label>
<div class="col-sm-6" id="newCast">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="btnAddMovie" data-dismiss="modal">Save</button>
</div>
</div>
</div>
When btnAddMovie is clicked I ajax / jquery method is called which calls a method in my controller. But before I submit I would like to validate the fields they have entered.
I am following this Form validation on bootstrap modal
I have declared my implementation as follows:
$(document).ready(function() {
$('#NewMovie').formValidation({
framework: 'bootstrap',
excluded: [':disabled'],
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
Title: {
validators: {
notEmpty: {
message: 'The Title is required'
}
}
}
}
});
});
My ajax method is as follows:
$("#btnAddMovie").click(function () {
var stringArr = $('span[data-id="cast[]"]').map(function () {
return $(this).text().trim();
}).get();
$.ajax({
url: '/Movies/Add',
traditional: true,
data: { "Title": $("#Title").val(), "Classification": $("#Classification").val(), "Rating": $("#Rating").val(), "ReleaseDate": $("#ReleaseDate").val(), "Cast": stringArr },
cache: false,
type: "POST",
success: function (result) {
if (result.success) {
}
},
error: function (result) {
alert("Error");
}
});
});
But for some reason when ever click the button on my form it automatically posts back without doing the validation?
I'm trying to validate and depending on if its true or false then perform the relevant action.
About your button, either you have to change it to a submit button or use the button setting to indicate which button should trigger the validation (see bellow)
button: {
// The submit buttons selector
selector: '#btnAddMovie'
}
you have to delete data-dismiss="modal" from your button
And then trigger the success.form.fv event and call your ajax method there, see following code:
$('#NewMovie').formValidation({
framework: 'bootstrap',
excluded: [':disabled'],
// ...
icon: {
// ...
},
fields: {
// ...
}
})
.on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
// And then
// Place your Ajax call here
var stringArr = $('span[data-id="cast[]"]').map(function () {
return $(this).text().trim();
}).get();
$.ajax({
url: '/Movies/Add',
traditional: true,
data: { "Title": $("#Title").val(), "Classification": $("#Classification").val(), "Rating": $("#Rating").val(), "ReleaseDate": $("#ReleaseDate").val(), "Cast": stringArr },
cache: false,
type: "POST",
success: function (result) {
if (result.success) {
}
},
error: function (result) {
alert("Error");
}
});
// And then close your modal
$('#MyModal').modal('hide');
});
# References:
form events docs: http://formvalidation.io/settings/#event-form
button setting docs: http://formvalidation.io/settings/#form-button
If you remove your ajax call, does the validation work?
Maybe you should take a look at your submit button :
<button type="button" class="btn btn-default" id="btnAddMovie" data-dismiss="modal">Save</button>
which is not a submit button.
If you look to the example in the page you gave us, you can see that the submit button's code is
<button type="submit" class="btn btn-primary">Login</button>
Try to change this and it would be nice if you could provide us a JSFiddle
Hope it's gonna help you a bit.
hi im using bootstrapValidator to validate my form and i have no idea where to add ajax request after validating form. and also want to prevent closing bootstrap modal after submitting the form. i referred similar questions and still couldn't make it work.
here is my bootstrap modal
<a href="#"class="btn btn-lg btn-black ico-windows" data-backdrop="static" data-keyboard="false" data-toggle="modal" data-target="#AddAlbum" > Create New Album </a>
<!-- Modal -->
<div class="modal fade" id="AddAlbum" 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"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Create New Album</h4>
</div>
<div class="modal-body">
<div id="formregister">
<form action="" class="form-horizontal" role="form" id="newAlbum" >
<p class="qc-errmsg" style="display: none;"> </p>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Album Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" name="albumName" placeholder="Album Name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label" >Description</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" name="description"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" onclick="send()" value="cart" class="btn btn-primary">Save Changes</button>
</div>
</div>
</form>
</div> <!-- form register -->
<div id="successfulpost" style="font: bold 12px Verdana, Arial, Helvetica, sans-serif; color: #ff0000; display: none;">
<p class="jst-txt"><span>Thank you,</span> for showing your Interest !!</p>
<p class="jst-txt">Our property advisor shall get in touch with you very shortly..</p>
</div>
</div> <!-- model body-->
</div>
</div>
</div>
here is my javascript
$(document).ready(function () {
//validations
$('#newAlbum').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
albumName: {
message: 'The Album Name is not valid',
validators: {
notEmpty: {
message: 'The Album Name is required and cannot be empty'
},
stringLength: {
min: 6,
max: 30,
message: 'The Album Name must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9]+$/,
message: 'The Album Name can only consist of alphabetical and number'
}
},
//form.submit();
}
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
url: "add_album.php",
type: "POST",
success: function () {
alert('done');
$('#newAlbum').hide();
$('#successfulpost').show();
}
});
});
i made a jsbin for this
http://jsbin.com/xatog/8/edit?html,js,output
You are using version 0.5.3. They have removed the submithandler option and added an event success.form.bv.
$(form)
.bootstrapValidator(options)
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
validator = $form.data('bootstrapValidator'),
submitButton = validator.getSubmitButton();
// Do whatever you want here ...
});
source here
Fiddle here