Client Side validations not working in jQuery UI Dialog - javascript

I searched and found lot of answers, still i am not able to validate fields in my jQuery UI Dialog. Please suggest appropriate ways for the same.
Parent View:
<div id="dialog" title="Add New">
<p>Div content</p>
</div>
<script type="text/javascript">$(function () {
$('#btnAddNew').click(function () {
$('#dialog').dialog
({
autoOpen: true,
modal: true,
open: function (event, ui) {
$(this).load("#Url.Action("AddNewFormPart1")"); //Rendering Partial View
}
});
});
});
<script/>
Partial View:
#using (Html.BeginForm("SubmitFormPart1", "Home", FormMethod.Post, new { #id = "formPart1" }))
{
#Html.ValidationSummary()
<div>......
<input type="submit" value="Submit" id="btnSubmitFormPart1"/>
</div>
}

Validator should parse partial page after loading partial page. if you are using Unobtrusive Validation:
$(this).load('#Url.Action("AddNewFormPart1")', function(response, status, xhr){
var form = $("#AddNewFormPart1");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
})

It is because your content are loaded after the plugin call!
You need to call the validation plugin after loading the partial view as follows(Notice the .done(function*({}) helper).
<script type="text/javascript">$(function () {
$('#btnAddNew').click(function () {
alert('Add New clicked!');
$('#dialog').dialog
({
autoOpen: true,
modal: true,
open: function (event, ui) {
$(this).load("#Url.Action("AddNewFormPart1")").done(function(){
//CALL YOUR VALIDATION PLUGIN HERE
//$('#formPart1').validate({...});
}); //Rendering Partial View
}
});
});
});

Related

Clearing jQuery Dialog validate upon open

I am encountering similar behaviour in my code: https://codepen.io/iw3/pen/BAdIq
html
<input id="open" type="button" value="Open" />
<div id="dialog">
<form id="form">
<input type="text" name="field" />
</form>
</div>
JS
$(function () {
$('#dialog').dialog({
autoOpen: false,
buttons: {
'Send': function() {
if ($('#form').valid()) {
alert('Success');
$('#dialog').dialog('close');
}
}
}
});
$('#open').on('click', function() {
$('#dialog').dialog('open');
});
$('#form').validate({
rules: {
field: {
required: true,
digits: true,
maxlength: 9,
min: 1
}
}
});
});
When the user enters data in the form and gets an error, then closes the form and reopens it, the validate messages in red remain while they should really be cleared. Is this an intended behavior or is there a way to reset the validate?
To fix this you can simply hide the validation error label elements when the dialog is closed:
$('#dialog').dialog({
autoOpen: false,
close: function() {
$('label.error').hide();
},
// other configuration settings...
});
Alternatively you can save a reference to the validator and call resetForm() on it when the dialog is closed:
let validator = $('#form').validate({
rules: {
// your rules...
}
});
$('#dialog').dialog({
autoOpen: false,
close: function() {
validator.resetForm();
},
// other configuration settings...
});

HTML form default action is running if jqueryui dialog div content change to original content

i am displaying html form inside jqueryui dialog and i am using jquery validation plugin to validate it.
Problem - when i submit form by changing content to original, default form action is running.
It is only happening if i change html content to original content before form closing.
Here is my code:
$(document).ready(function() {
var getOldForm = $("#send-pm-win").html();
$("#pmLink").click(function() {
$("#send-pm-win").dialog({
modal: true,
draggable: false,
resizable: false,
autoOpen: true,
buttons: [{
text: "Cancel",
click: function() {
$(this).dialog("close");
},
style: "outline: none;"
}],
close: function(event, ui) {
$("#send-pm-win").html(getOldForm);
$(this).dialog("destroy");
}
});
});
});

Ajax.BeginForm() post method not returning Partial View

I have a MVC application and I'm trying to insert properties of objects. For that, I made a modal popup via jQuery dialog. I don't want it interfering with other actions that the user is doing, so I made an Ajax.BeginForm. I hoped that when I do the insert, it will close on return PartialView(), but it opens the popup View on full screen instead of closing the dialog. Also, it is important that the base view should be dynamic, so you can open the dialog on any page and not make a postback.
I've read the other similar issues and couldn't resolve my problem.
There are some similar issues, but none of them
Please, help me to achieve the proper function if possible. Code below:
JS:
<script>
$(document).ready(function () {
var url = "";
$("#dialog-alert").dialog({
title: 'Error encountered!',
autoOpen: false,
resizable: false,
width: 350,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true
});
if ('#TempData["msg"]' != "") {
$("#dialog-alert").dialog('open');
}
$("#lnkServer").on("click", function (e) {
//e.preventDefault(); //use this or return false
url = $(this).attr('href');
$('#dialog-edit').dialog({ title: "Add a new Server" });
$("#dialog-edit").dialog('close');
$("#dialog-edit").dialog('open');
return false;
});
$("#lnkIssType").on("click", function (e) {
//e.preventDefault(); //use this or return false
url = $(this).attr('href');
$('#dialog-edit').dialog({ title: "Add a new Issue Type" });
$("#dialog-edit").dialog('close');
$("#dialog-edit").dialog('open');
return false;
});
$("#lnkUser").on("click", function (e) {
//e.preventDefault(); //use this or return false
url = $(this).attr('href');
$('#dialog-edit').dialog({ title: "Add a new User" });
$("#dialog-edit").dialog('close');
$("#dialog-edit").dialog('open');
return false;
});
$("#lnkDept").on("click", function (e) {
//e.preventDefault(); //use this or return false
url = $(this).attr('href');
$('#dialog-edit').dialog({ title: "Add a new Department" });
$("#dialog-edit").dialog('close');
$("#dialog-edit").dialog('open');
return false;
});
$("#dialog-edit").dialog({
autoOpen: false,
resizable: false,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
//$(".ui-dialog-titlebar-close").hide();
$(this).load(url);
}
//buttons: {
// "Cancel": function () {
// $(this).dialog("close");
// }
//}
});
});
function onSuccess() {
$("#dialog-edit").dialog('close');
}
</script>
Form:
<div id="container">
#using (Ajax.BeginForm("AddDept", new AjaxOptions { OnSuccess = "onSuccess" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div>
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.Department_Name)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Department_Name, htmlAttributes: new { #class = "form-control text-box single-line input-properties", placeholder = "Collections" })
</div>
<div class="editor-label">
#Html.ValidationMessageFor(model => model.Department_Name)
</div>
<input type="submit" value="Submit" class="btn btn-default btn-add-properties" />
</fieldset>
</div>
}
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddDept([Bind(Include = "Department_Name")] Department #dept)
{
try
{
if (ModelState.IsValid)
{
db.Departments.Add(#dept);
db.SaveChanges();
TempData["Msg"] = "Data has been saved successfully";
return PartialView();
//return Redirect(System.Web.HttpContext.Current.Request.UrlReferrer.PathAndQuery);
}
}
catch
{
TempData["Msg"] = "Probably the record already exists. If not, contact Georgi Georgiev, RA Dept.";
return PartialView();
}
return PartialView(#dept);
}
My problem was probably due to that my Ajax.BeginForm popup View relied on different ActionResult in the controller compared to the Background View's.
Anyway, it turns out that I couldn't achieve my functionality without having a POST through Ajax.
Here's what I did (in Layout view):
$("#dialog-edit").dialog({
autoOpen: false,
resizable: false,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
//$(".ui-dialog-titlebar-close").hide();
$(this).load(url);
},
buttons: [{
text: "Submit",
"class": "btn-add-properties",
click: function () {
var form = $('form', this);
$.post(form.prop('action'),
form.serialize(),
function (response) {
alert("success");
})
.fail(function () {
alert("error");
});
$("#dialog-edit").dialog('close');
}
}]
});
The ajax post is the function under the dialog button.

MVC 4 Actionlink to prompt Jquery Confirmation Dialog

I'm implementing an actionlink to perform delete. Initially was using javascript confirmation box. Due to customer request to change the confirmation box header text, i need to use jquery confirmation dialog. It will straight perform delete without prompting the dialog box when i click the link. Please help me. Thanks!
My View & Actionlink:
#Html.ActionLink("Remove", "SURV_Admin_Group_Delete", "SURV_Admin", new { id = Model[i].GroupID }, new { #class = "modal" })
<div id="dialog-confirm"></div>
Jquery dialog script:
$('.modal').click(fnOpenNormalDialog);
function fnOpenNormalDialog() {
$("#dialog-confirm").html("Confirm Dialog Box");
// Define the Dialog and its properties.
$("#dialog-confirm").dialog({
resizable: false,
title: "Modal",
height: 250,
width: 400,
buttons: {
"Yes": function () {
return true;
},
"No": function () {
return false;
}
}
});
}
My Delete Controller:
public ActionResult SURV_Admin_Group_Delete(int id)
{
SURV_Group_Model surv_group_model = db.SURV_Group_Model.Find(id);
db.SURV_Group_Model.Remove(surv_group_model);
db.SaveChanges();
return RedirectToAction("SURV_Admin_Create_Group");
}

jQuery UI: model dialog 'close'

I have 2 Razor views where one is loading the other in a jQuery UI dialog. In the view that get loaded in the dialog; I am opening another jQuery UI dialog to display a message.
The objective is to close both the dialogs when message dialog Cancel button is clicked.
Razor code is as follows:
Main View
<button id="openModel" onclick="openModel()">
<div id="mainDialog" />
<script type="text/javascript">
function openModel() {
$('#mainDialog').dialog({
open: function () {
// loading "the secondary view in the model dialog"
// url: controller-action url to load the second view
$(this).load('url');
}
});
}
</script>
Dialog View
<button id="messageOpener">Verify</button>
<div id="messageDialog" />
<script type="text/javascript">
$(document).ready(function () {
$("#messageOpener").click(function () {
$("#messageDialog").dialog("open");
return false;
});
$("#messageDialog").dialog({
buttons: {
Retry: function () {
$(this).dialog("close");
},
Cancel: function () {
// **** ?? must close both dialogs. ****
}
},
autoOpen: false,
});
});
</script>
I have tried following approaches to close the dialogs:
Approach 01:
$(".ui-dialog-content").dialog("close");
Approach 02:
$(this).dialog("close");
$("#mainDialog").dialog("close");
Approach 03:
$(".ui-dialog:visible").find(".dialog").dialog("close");
But all above does not close the dialogs as expected instead produces the following JS error:
Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
v.extend.error
(anonymous function)
v.extend.each
v.fn.v.each
e.fn.(anonymous function)
$.dialog.buttons.Cancel
r.click
v.event.dispatch
o.handle.u
Re-writing the code in the following way solve the problem..
1. Main View
<button id="openModel" onclick="openModel()">
<div id="mainDialog" />
<script type="text/javascript">
var $modelDialog = $('#mainDialog').dialog({
autoOpen: false,
open: function () {
// loading "the secondary view in the model dialog"
// url: controller-action url to load the second view
$(this).load('url');
}
});
function openModel() {
$modelDialog.dialog('open');
}
function closeModel() {
$modelDialog.dialog('close');
}
</script>
2. Dialog View
<button id="messageOpener">Verify</button>
<div id="messageDialog" />
<script type="text/javascript">
var $messageDialog;
$(document).ready(function () {
$("#messageOpener").click(function () {
$messageDialog.dialog("open");
return false;
});
$messageDialog = $("#messageDialog").dialog({
buttons: {
Retry: function () {
$messageDialog.dialog("close");
},
Cancel: function () {
// [!!]
$messageDialog.dialog("destroy");
closeModel();
}
},
autoOpen: false,
});
});
</script>
Approach 2 looks fine , but you get that error cause the mainDialog modal is not opened when you try to close the message dialog. Also, function openModel is not getting called anywhere.

Categories

Resources