how to submit form loaded on the bootstrap popover?
On click on a button ,a form will be loaded on popover & the same form user should be able submit it by pressing ENTER key. check this fiddle
i tried like this but its loaded whole page
$('#popoverId').popover({
html: true,
title: 'Popover Title<a class="close" href="#");">×</a>',
content: $('#popoverContent').html(),
});
$('#popoverId').click(function (e) {
e.stopPropagation();
});
$(document).click(function (e) {
if (($('.popover').has(e.target).length == 0) || $(e.target).is('.close')) {
$('#popoverId').popover('hide');
}
});
//--------------script to to submit form after validation -------------
$(".popover").parent().find('#something').validate({
rules: {
sproject_name: {
minlength: 3,
maxlength: 15,
required: true
}, tooltip_options: {
sproject_name: {placement: 'center', html: true, trigger: 'focus'}
}
},
submitHandler: function(e) {console.log("ajax logi goes here....");
}
});
html code
<h3>Live demo</h3>
<button id="popoverId" class="popoverThis btn btn-large btn-danger">Click to open form</button>
<div id="popoverContent" class="hide">
<form method="post" name="project-forms" id="something"><input class="red-tooltip" id="sadd_project_id" name="sproject_name" type="text" required/></form>
</div>
You need to use .validate inside #popoverId click. Because, you are using it on page load and at that time popover form still not exist. You can see following code and demo for bets understanding;
$('#popoverId').click(function (e) {
e.stopPropagation();
$('#something').validate({
rules: {
sproject_name: {
minlength: 3,
maxlength: 15,
required: true
}
},
submitHandler: function(form) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
dataType : 'json'
})
.done(function (response) {
if (response.success == 'success') {
alert('success');
} else {
alert('fail');
}
});
return false;
}
});
});
See working demo here: Demo
Related
I have a form that uses jQuery.validate.js plugin to validate and submit a form. The form contains a file upload.
I want to submit and upload the image with the validate.js but When I submit the form with the selected image, nothing happens. I've searched for solution, but the ones I got did not solve the problem.
// **EDIT**
// Add method to check imagesize
$.validator.addMethod("imageSize",function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param);
}, "This fileld is required.");
// END: **EDIT**
var addNewsForm, format;
addNewsForm = $("#newsPanel");
format = ['png','jpe?g','gif'];
addNewsForm.on("submit", function(e) {
e.preventDefault();
//validate form
$(this).validate({
errorClass : "error",
rules : {
news_image : {
required : true,
imageSize: 5242880,
accept : format
}
},
messages : {
news_image : {
required : "Please select an image for the news.",
imageSize : "Image size should not be greater than 5MB.",
accept : "Unsupported image format"
},
submitHandler : function(form) {
sendData = {
news_image : $("#newsImage")
}; // end of sendData
$(form).ajaxSubmit({
type : "POST",
data : sendData,
url : "action_news.php",
success : function(getData) {
$("#pageMsg").html(getData);
}
}); // end of ajaxSubmit
}, // end of submitHandler
}); // end of document ready
<form method="get" id="newsPanel" enctype="multipart/form-data">
<div id="pageMsg"></div>
<input type="file" id="newsImage" name="news_image" size="40" id="newsImage">
</form>
Any better way of achieving this?
You're missing a closing } for your messages object, right now the submitHandler is inside the messages object.
You're also missing a }) to close this function addNewsForm.on("submit", function (e) {.
Try using the code below and see if it works.
addNewsForm.on("submit", function (e) {
e.preventDefault();
//validate form
$(this).validate({
errorClass: "error",
rules: {
news_image: {
required: true,
imageSize: 5242880,
accept: format
}
},
messages: {
news_image: {
required: "Please select an image for the news.",
imageSize: "Image size should not be greater than 5MB.",
accept: "Unsupported image format"
},
},
submitHandler: function (form) {
sendData = {
news_image: $("#newsImage")
}; // end of sendData
$(form).ajaxSubmit({
type: "POST",
data: sendData,
url: "action_news.php",
success: function (getData) {
$("#pageMsg").html(getData);
}
}); // end of ajaxSubmit
}, // end of submitHandler
}); // end of document ready
})
I have a form , after validate I take data and update the hidden form that I popup or just need to be hidden and need to be posted to the action.
from hidden I do manual submit from code
the bug is that always post by submit lead to refresh the page instead. redirecting
my js code:(could be typo) . - form validate
form.validate({
ignoreTitle: true,
onfocusout: function (element) {
if (!this.checkable(element)) {
this.element(element);
}
},
onkeyup: false,
rules: {
firstName: {required: true, minlength: 2, maxlength: 45},
lastName: {required: function () {
return checkField("lastName")
}, minlength: 2, maxlength: 45},
},
messages: {
firstName: {required: FieldRequiredStr, minlength: invalidFirstName, maxlength: invalidFirstName},
lastName: {required: FieldRequiredStr, minlength: invalidLastName, maxlength: invalidLastName},
},
onsubmit: true,
submitHandler: function (frm) {
if(!form.valid())return;
$("#send",form).attr('disabled', 'disabled');
$("#send",form).addClass('sent');
form.ajaxSubmit(
{
url: "api.php",
dataType: 'xml',
success: function (response) {
var xml;
if (typeof response == 'string') {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(response);
}
var url = "https://url/login"
console.log(url);
$('#frm2').attr('action', url );
$('#email').val($("#email",frm).val());
$('#password').val($("#password",frm).val());
// $.fancybox({href: '#make-deposit'});
//$("#frm2").submit();
//
setTimeout(function () {
$("#frm2").submit();
}, 2000);
}
}
});
},
errorPlacement: function (error, element) {
//this is working good
// A bit ugly.
}
my hidden form (even if it is not hidden click on submit will casue refresh)
<div style="display:none;">
<form id="frm2" method="post" action="https://url/login" target="">
<input type="hidden" id="email" name="email" value="" />
<input type="hidden" id="password" name="password" value="" />
<input class="dbtn" type="submit" name="btn" id="btn" value="btn" />
</form>
</div>
It's working without slash at the end in the url on action
But the post data is not send in that case
It happens because the form IS submitted. You need to return false in your submithandler, like this:
submitHandler: function (frm) {
//Your code here
return false;
}
in submit handler function, use
e.preventDefault();
e.stopPropogation();
where e being the event passed.
I have one form and fields are Fullname, Password and Mobile no and each field has the single button. All the fields are displaying single in the page. If the user clicked on the button then next field will display but I have to set the validation on it using AJAX. I have to display the error single on each field. Would you help me in this?
I tried below code but I am getting false output in the alert.
My controller
public function submit_from(){
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('fullname', 'fullname', 'required|min_length[5]|max_length[20]|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|min_length[5]|max_length[20]|trim|xss_clean');
$this->form_validation->set_rules('mobile', 'mobile', 'required|min_length[5]|max_length[20]|trim|xss_clean');
if ($this->form_validation->run() == FALSE)
{
echo validation_errors();
}
else
{
echo "true";
}
}
View
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#password_form, #mobile_form{
display: none;
}
</style>
</head>
<body>
<form class="active_form" name="form_1" method="post">
<div id="name_form">
<!--Name form********************************************************-->
<label>Full name</label>
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<?php echo form_error('fullname'); ?>
<button type="button" id="continue_to_password">Continue to Password</button>
</div>
<!--password form********************************************************-->
<div id="password_form">
<label>Password</label>
<input type="password" name="password" id="password" placeholder="password name">
<?php echo form_error('password'); ?>
<button type="button" id="continue_to_mobile">Continue to mobile no</button>
</div>
<!--mobile form********************************************************-->
<div id="mobile_form">
<label>Mobile number</label>
<input type="text" name="mobile" id="mobile" placeholder="mobile no">
<?php echo form_error('mobile'); ?>
<button type="submit">Submit</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('form[name="form_1"]').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '<?php echo base_url("index.php/testcontroller/submit_from"); ?>',
data: $('form[name="form_1"]').serialize(),
success: function (data) {
alert(data);
}
});
});
});
/*When clicked on button*/
$('body').on('click', '#continue_to_password', function(e) {
$('#name_form').hide();
$('#password_form').show();
});
$('#continue_to_mobile').on('click', function() {
$('#password_form').hide();
$('#mobile_form').show();
});
</script>
</body>
</html>
I tried client side validation using Jquery but this is also working at the end when I clicked on submit button.
Jquery
$(document).ready(function() {
$(".active_form").validate({
rules: {
fullname: {
required: true,
minlength:3,
maxlength:50
},
password: {
required: true,
minlength:3,
maxlength:50
},
mobile: {
required: true,
minlength:3,
maxlength:50
}
},
})
$('#continue_to_password').click(function() {
$(".active_form").valid();
});
});
You may see the result of your validation:
if ($this->form_validation->run() == FALSE) {
echo validation_errors();
}
Please see this post it may help you...
Do form validation with jquery ajax in codeigniter
For validation using jQuery with ajax submit you can try this script.
jQuery(function($){
$(".active_form").validate({
rules: {
fullname: {
required: true,
minlength:3,
maxlength:50
},
password: {
required: true,
minlength:3,
maxlength:50
},
mobile: {
required: true,
minlength:3,
maxlength:50
}
},
submitHandler: function (form) {
var request;
// bind to the submit event of our form
// let's select and cache all the fields
var $inputs = $(".active_form").find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $(".active_form").serialize();
//alert(serializedData);
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
request = $.ajax({
url: "http://ajax/function/url/here",
type: "POST",
data: serializedData,
});
// callback handler that will be called on success
request.done(function(data) {
// log a message to the console
alert("success awesome");
});
request.fail(function (jqXHR, textStatus, errorThrown) {
// log the error to the console
});
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
}
});
});
Finally, I found My solution. I don't know it's the correct way to do but it's solved my issue.
$(document).ready(function() {
$("form[name='form_1']").validate({
rules: {
fullname: {
required: true,
minlength:3,
maxlength:50
},
password: {
required: true,
minlength:3,
maxlength:50
},
mobile: {
required: true,
minlength:3,
maxlength:50
}
},
})
$('body').on('click', '#continue_to_password', function(e) {
if($("form[name='form_1']").valid())
{
$('#name_form').hide();
$('#password_form').show();
}
});
$('#continue_to_mobile').on('click', function() {
if($("form[name='form_1']").valid()){
$('#password_form').hide();
$('#mobile_form').show();
}
});
});
HTML5 validation isn't working in Safari so I'm using Happy.js.
My form is still submitting via ajax in Safari though with the code below (here is JSFiddle).
How can I validate #email-input before sending the form with ajax?
The code below is checking if ($(this).hasClass('unhappy')) then don't submit form, if it doesn't have class unhappy then submit form. But I guess the problem is that it doesn't have class unhappy from the beginning.
used from this reference: isHappy.js allowing ajax call when not valid
$(document).ready(function() {
function ajaxEmailForm() {
$(".sendingEmailLink, .sentEmailLink").hide();
$('#email-form').submit(function(event) {
event.preventDefault();
var formserialize = $(this).serialize();
var submitButton = $('#submitEmailForm');
$.ajax({
type: 'POST',
url: 'https://formkeep.com/f/MYID',
accept: {
javascript: 'application/javascript'
},
data: formserialize,
beforeSend: function() {
$(".sendEmailLink").hide();
$('.sendingEmailLink').show();
},
complete: function() {
$(".sendingEmailLink").hide();
},
success: function(d) {
$('.sentEmailLink').show();
},
error: function() {
$('.notification-e--phone').slideDown("medium", function() {});
},
}).done(function(data) {
submitButton.prop('disabled', 'disabled');
});
});
};
$('#email-form').isHappy({
fields: {
'#email-input': {
required: true,
test: happy.email,
message: 'Please enter your full email address.',
errorTarget: '.email-input-error'
}
}
});
var is_unhappy = false;
$('#email-form div :input').each(function(i) {
if ($(this).hasClass('unhappy')) {
is_unhappy = true;
return false;
}
});
if (!is_unhappy) {
ajaxEmailForm();
};
});
I have a form with two buttons
a) Test - on click of the button a javascript function is called to verify a couple of credentials.
b) Create - on click of the button a javascript function is called to save the form.
#Messages("playauthenticate.project.create")
I have a form tag around these two submit buttons with no action.
name, description, accessKey and secretKey are the four fields in the form.
on clicking on the create button, I want to perform jquery validation and then submit the form but the jquery validation submitHandler is not getting called in the javascript function and there are no errors in the Error Console.
When I click on the create button, the create alert is shown and then the form resets and I am able to see all the parameters entered in the URL.
$("create").click(function() {
alert("create ");
$('#projectForm').validate( {
rules: {
name: {
minlength: 6,
required: true
},
description: {
required: true,
description: true
},
accessKey: {
minlength: 10,
required: true
},
secretKey: {
minlength: 15,
required: true
}
},
focusCleanup: false,
wrapper: 'div',
errorElement: 'span',
highlight: function(element) {
$(element).parents ('.control-group').removeClass ('success').addClass('error');
},
success: function(element) {
$(element).parents ('.control-group').removeClass ('error').addClass('success');
$(element).parents ('.controls:not(:has(.clean))').find ('div:last').before ('<div class="clean"></div>');
},
errorPlacement: function(error, element) {
error.appendTo(element.parents ('.controls'));
},
submitHandler: function() {
alert("hello");
var name = $('#name').val();
var description = $('#description').val();
var accessKey = $('#accessKey').val();
var secretKey = $('#secretKey').val();
var dataString = 'name='+ name + '&description=' + description + '&accessKey=' + accessKey+ '&secretKey=' + secretKey;
//alert(dataString);
$.ajax({
type: "POST",
url: "/demo/save",
data: dataString,
success: function(data) {
$('#result').html("<h2>demo created successfully!</h2>");
},
error: function(data) {
$("#result").html("<h2>Error!</h2>");
}
})
}
});
});
JSfiddle - http://jsfiddle.net/NJxh5/3/
Thank you
.validate() is the method for initializing the plugin. It's not a method of testing the form. Testing is automatic.
Therefore, get rid of the click handler. The click event is captured automatically by the plugin. If the form is valid, the submitHandler will fire.
Otherwise, you are doing it properly by placing your ajax inside the submitHandler callback.
$(document).ready(function () {
$('#projectForm').validate({ // initialize the plugin
// rules & options
submitHandler: function(form) {
// ajax method
}
});
});
Working DEMO: http://jsfiddle.net/ACdtX/
With two different buttons and actions:
HTML:
<form id="projectForm">
....
<input type="button" class="button" value="TEST" id="test" />
<input type="button" class="button" value="Create" id="create" />
</form>
jQuery:
$(document).ready(function () {
$('.button').each(function () {
$(this).on('click', function () {
var action;
if ($(this).attr('id') == "test") {
action = 'test.php';
} else {
action = 'create.php';
}
$('#projectForm').submit();
});
});
$('#projectForm').validate({ // initialize the plugin
// rules & options
submitHandler: function(form) {
// ajax method
$.ajax({
url: action, // determined from click handler above
// ajax options
});
}
});
});