jQuery Validate not working with Ajax and jQuery dialog - javascript

On my website I have a navigation and a main content area. When you click on a navigation link, the content inside the main content area always gets loaded via ajax. If you click the link "Contact", a text gets loaded which contains a link for a jQuery dialog which contains the contact form.
The problem: When you load the website and navigate to the contact form area, the validation works perfectly fine. However, if you navgiate away to another content area (= another content gets loaded via ajax) and then go back to the contact form area and click the submit button (WITHOUT reloading the page in between), validation fails, gets ignored and the form action gets executed. If you reload the page and then navigate to the contact form area, everything works again.
I cannot make sense of this behaviour. What is weird: Validating another form in the content area which is NOT opened in a jQuery dialog always works, no matter what you had clicked before. So it must be because of the jQuery dialog popup and Ajax. Who can make sense of this problem?
Here comes my code:
HTML:
open form test popup
<div id="popup-form-test">
<form id="form-test" action="somelink">
<input type="text" placeholder="testtext eingeben" name="testText"></input>
<input type="submit" value="submit">
</form>
</div>
JS:
var dialogTest = $("#popup-form-test").dialog({
autoOpen: false,
modal: true,
close: function () {
console.log('closed');
}
});
$("#open-popup-form-test").on("click", function () {
dialogTest.dialog("open");
});
$('#form-test').validate({
debug: true,
rules : {
testText: {
required: true
}
},
submitHandler: function(form) {
alert('submitted');
}
});

you must use the open callback of .dialog() and insert there the validator:
var dialogTest = $("#popup-form-test").dialog({
autoOpen: false,
modal: true,
open : function (event, ui) {
$('#form-test').validate({
debug: true,
rules : {
testText: {
required: true
}
},
submitHandler: function(form) {
alert('submitted');
}
});
},
close: function () {
console.log('closed');
}
});
i can't test without a valid example but it should work.

Related

Bootbox dialog doesn't open within a loop

This is my objective:
Custom Bootbox dialog opens to specify a value. User specifies a value, clicks Save and the value is passed to web application via Ajax call.
Web application validates the value and either sends back a "success" message if validation was passed and database was updated or sends back a "failure" message with a reason for a validation failure.
If "success" message was received dialog closes, otherwise it opens again and displays validation message below user input. User can change the input and click Save again or press Cancel to dismiss the dialog.
MCVE (note that while(bContinue == true) is commented out to show that it works without a loop and there is no validation message anywhere but it will be a part of a Message variable (this variable will be updated in Save callback function after an Ajax call)):
$(document).on("click", ".alert", function(e) {
var Message = "<label class='control-label col-sm-1' style='width:30px;' for='assignmentname'>"+"Assignment "+"</label>"
+ "<input type='text' id='assignmentname' class='form-control' style='float: left; max-width:800px;' value='Initial value'>"
var bContinue = true;
//while(bContinue == true)
{
bootbox.dialog({
size: "large",
message: Message,
title: "Edit Assignment",
buttons: {
save:
{
label: "Save",
className: "btn btn-success",
callback: function() {
// perform Ajax call to the web application
// and set bContinue to true or false depending on
// return value
bContinue = true;
}
},
cancel:
{
label: "Cancel",
className: "btn btn-default",
callback: function() {
// exit out of the loop
bContinue = false;
}
}
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://github.com/makeusabrew/bootbox/releases/download/v4.4.0/bootbox.min.js"></script>
<p><a class="alert" href=#>Click here</a></p>
The problem is - as soon as while(bContinue == true) is un-commented the dialog never opens.
Expected MCVE behavior: dialog opens and if Save is clicked it closes and re-opens. If Cancel is clicked - dialog closes.
The problem is not in the Bootbox , the problem is in the while loop which keep looping very fast without waiting the Bootbox to load, and it make the whole browser hang :)
So you will need to change your logic, may be put the Bootbox dialog in a function and make it call the function again on save.
Or may be using promises: How to use confirm alert and return an AJAX promise?

Jquery validation plugin | resetForm is not working

I am trying to clear all error messages as well error highlighting when user click on the clear form button, below are actual requirements
Validate form using Jquery validation
When user click on a field error message should be cleared (per field)
On clicking reset button, every error should be cleared
here is my code
$( document ).ready(function(){
var validator = $("#register_form").validate({
validator.resetForm();
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
For me, first 2 things are working, but when I am trying to clear complete form, I am not able to do this.this is how I am trying to clear it
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
}
But nothing is happening , though with $("#register_form")[0].reset();, form fields are getting clear, but error messages are not getting cleared.
Quote OP:
1) Validate form using Jquery validation
You cannot put the validator.resetForm(); method inside of the .validate() method.
.validate() is a plugin method where the only thing that can go inside is a comma separated map of the allowed options, {option:value, option:value, etc.}, as per the .validate() method documentation.
resetForm() method documentation
$("#register_form").validate({
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
cell: {
required: true
}
},
messages: {
// custom messages
}
});
.validate() method DEMO: http://jsfiddle.net/P46gL/
Quote OP:
2) When user click on a field error message should be cleared (per field)
This is thanks to the focusCleanup option. As you've already done, set it to true and when you click on the field with an error, the error clears.
$("#register_form").validate({
focusCleanup: true,
rules: {
....
focusCleanup DEMO: http://jsfiddle.net/P46gL/1/
Quote OP:
3) On clicking reset button, every error should be cleared
You would call the resetForm() method from within a click handler of the reset button. This will immediately remove all error messages from the entire form and reset the validation plugin to its initial state.
$('#clearform').on('click', function () {
$("#register_form").validate().resetForm(); // clear out the validation errors
});
Make sure the reset button is type="button" or type="reset" or it will trigger validation.
<input type="reset" id="clearform" value="reset form" />
Clear Errors DEMO: http://jsfiddle.net/P46gL/3/
Clearing out the field data
You can clear out the values of the fields by calling a JavaScript .reset() like this.
$('#clearform').on('click', function () {
var form = $("#register_form");
form.validate().resetForm(); // clear out the validation errors
form[0].reset(); // clear out the form data
});
Full Working DEMO: http://jsfiddle.net/P46gL/4/
$("#register_form")[0].reset();, form fields are getting clear, but error messages are not getting cleared.
to do this you can put one more line below it:
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
$('.error').hide();
}
Although you should do this way:
$( document ).ready(function(){
var validator = $("#register_form").validate({
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
$('[type="reset"]').on('click', function(){
validator.resetForm();
});
});
You should put your validator.resetForm(); in the click event of reset button.
If nothing works then try this approach (specially for clearing data purpose):
1- Form html:
<input type='reset' class="button_grey resetForm" value='Reset'>
2- Jquery validate
// you can add error fields
var validator = $("#clearform").validate({
focusCleanup: true
});
3- Reset the form
$('[type="reset"]').on('click', function(){
$("#clearform").closest('form').find("input[type=text], textarea").val("");
$('input:checkbox').removeAttr('checked');
validator.resetForm();
return false;
});
All error messages will be cleared
$('.btn-reset').on('click', function () {
$( "label.error" ).remove();
});

JQuery Dialog - only load when button click

Using JQuery Dialog http://jqueryui.com/dialog/#modal-confirmation
The dialog box appears whenever the page loads I only want it to appear when 'Remove Invoice' is clicked.
i've tried:<input id="RemoveInvoice" type="button" value="Remove Invoice" onclick="ConfirmDeleteInvoice()" />
then putting the actual JS inside a ConfirmDeleteInvoice function:
function ConfirmDeleteInvoice() {
// $(function () { //removed this line and added the above line
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Are you sure you want to delete this invoice": function () {
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
}
ERROR: JavaScript runtime error: 'ConfirmDeleteInvoice' is undefined
Sorry still a beginner at JS so please bear with.
Thanks
You've got an extra trailing }); right before your last closing brace, take that out and it'll work.
Also, in my fiddle you'll see I've added the click event in jQuery, as onclick inside HTML is considered bad practice. I did this by adding:
$("#RemoveInvoice").click(ConfirmDeleteInvoice);
See here: http://jsfiddle.net/P4VHw/

trigger an jQuery UI Dialog if user not authorized

On my website I have two ways to login. The first is used then an user is pushing the Logon button, which trigger an jQuery UI Dialog to open. The second is an normal view, which is used, if an user isn't Authorized, which redirect to an normal login view. But what i liked to do instead, is if an user is not Authorized, it opens the Login jquery ui dialog instead of redirection to the view the user is intended.
This is how i currently are opening the dialog,
$(".openLoginDialog").on("click", function (e) {
e.preventDefault();
$("<div></div>")
.addClass("dialog")
.attr("id", $(this).attr("data-dialog-id"))
.appendTo("body")
.dialog({
title: $(this).attr("data-dialog-title"),
create: function (event, ui) {},
close: function () { $(this).remove() },
open: function (event, ui) {},
modal: true,
position: ['center', 130],
minWidth: 510,
resizable: true,
zIndex: 20000
})
.load(this.href);
});
Because the content in the dialog is an partialView it's called like this:
<div class="items iconlogin highligth-br"><a class="openLoginDialog" data-dialog-id="LoginDialog" data-dialog-title="Login" href="#Url.Action("LogOn", "Authentication", new { returnUrl = Request.Url.ToString() })">Login</a></div>
Also to help me controlling the not Authorized, i have overriden this calls.
public override void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Authentication", action = "AccessDenied" }));
}
Last resort would be to redirect to an access denied page, with just an white background, which opens on load, a dialog.
I have a MVC intranet solution that employs functionality similar to what you describing, however it is using windows auth not forms.
Basically I have something like this in the Index...
var userExists = "#ViewBag.User";
// require the user to register if they are not found
if (userExists == "") {
$.get('Home/Register/', function (data) {
$("#Register").html(data);
$("#Register").dialog({
resizable: false,
closeOnEscape: false,
dialogClass: 'no-close',
typeDelay: 250
});
});
}
And then in the controller I just set 'ViewBag.User' to the username if they exist.
Have a look at this example:
http://jqueryui.com/dialog/#modal-form
Notice the autoOpen: false
I'm not familiar with asp.net so I wont be able to help with actual implementation. One approach would be to check where the request came from and if the user is not authorized redirect them back to that page and hit them with a dialog.
Another approach would be to know if the user is authenticated on the page load and override links that require authentication
$(".authRequired").on("click", function (e) {
e.preventDefault();
//fancy logic here to load form and dialog
});

Filling multiple divs with single ajax() call, form submit button fails

The short question is when I fill a <div> containing a type=submit button the .click(function(){...} function fails.
What I'm doing is this, #formDialogButton opens #accordion populated by .ajax() containing #userForm with an input type=submit. When client clicks submit it is supposed to fire .ajax() where php does database stuff and returns one of the #userform.
$(".formDialogButton").click(function(){
var userDialog = "#" + this.id + "Dialog";
$("#userForm, #siteForm, #limitForm").html("<img src='ajax-loader.gif' />");
$("#userForm, #siteForm, #limitForm").load("ajax.php", {op: "forms"}, function(responseTxt,statusTxt,xhr){
$("#userForm").html($("#user").html());
$("#siteForm").html($("#site").html());
$("#limitForm").html($("#limit").html());
if(statusTxt=="success") {
$(userDialog).dialog({
autoOpen: false,
draggable: true,
modal: true,
resizable: true,
width: 700,
position: { within: "#mainContent" }
});
$(userDialog).dialog("open");
$( "#accordion").accordion({
collapsible: true,
heightStyle: "content",
});
};
if(statusTxt =="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
This is working and returns a <input class="submitAndReturn" type="submit" value="Submit" /> in the form. But I can't "find" it to do anything.
$(".submitAndReturn").click(function() {
alert ('this is where I call my regular .formSubmitButton and let success: function() do a .formDialogButton ');
});
I'm a total self taught amateur so please forgive me and try to help. Thanks
Sounds like you are trying to add the click event before the element is loaded on the page. Change
$(".submitAndReturn").on("click", function() {
alert ('as .submit and return is dynamically loaded. so, use on function');
});
to
$(document).on("click", ".submitAndReturn", function(e) {
e.preventDefault(); //cancel the click action if needed
alert ('as .submit and return is dynamically loaded. so, use on function');
});
$(".submitAndReturn").on("click", function() {
alert ('as .submit and return is dynamically loaded. so, use on function');
});
What I'm doing is this, #formDialogButton opens #accordion populated by .ajax() containing #userForm with an input type=submit
If I understand it correct .formDialogButton DOM element is getting loaded in .ajax() callback event.
If you are loading the javascript in question above in header or at the page end, most likely the $(".formDialogButton").click(function() event is not getting attached to DOM.
This happens because the script has already fired before the AJAX has fetched the required DOM to which event has to be attached. You would need to attach the event in .ajax() success callback. Something like
$.ajax({
url: 'YOUR_URL_TO_FETCH_FORM',
success: function(data) {
// associate click
$(".formDialogButton").click(function() // rest of the code
}
});

Categories