Getting new full calendar event in bootstrap modal - javascript

I am using bootstrap modal to display event details. When the event will be clicked the start, end and title will be displayed in the popup.
The events are created using a boostrap modal form.
Here is the code
$(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
views: {
month: {
titleFormat: 'YYYY, MM, DD'
}
},
validRange: function(nowDate) {
return {
start: nowDate,
end: nowDate.clone().add(1, 'months')
};
},
navLinks: true,
selectable: true,
selectHelper: true,
select: function(start, end) {
startDate = moment(new Date(start)).format("MM-DD-YYYY");
$('#createBookingModal .modal-header .modal-title span').text(startDate);
$('#createBookingModal').modal('show');
},
editable: true,
eventLimit: true, // allow "more" link when too many events
events: function(start, end, timezone, callback){
$.ajax({
url: '/api/bookings',
dataType: 'json',
data: {
start: start.unix(),
end: end.unix(),
},
success: function(response){
var events = [];
$(response).each(function(){
events.push({
title: $(this).attr('title'),
start: $(this).attr('start_time'),
end: $(this).attr('end_time'),
});
});
callback(events);
}
});
},
eventClick: function(event, jsEvent, view) {
//Todo
//Get event end date here
console.log(event);
startDate = moment(new Date(event.start)).format("MM-DD-YYYY");
endDate = moment(new Date(event.end)).format("MM-DD-YYYY");
$('#modalTitle').text(event.title);
$('#modalBody .start span').text(startDate);
$('#modalBody .end span').text(endDate);
$('#fullCalModal').modal('show');
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
$('#submitButton').on('click', function(e){
e.preventDefault();
doSubmit();
});
function doSubmit(){
//validate end date here
endDate = new Date($('#bookingEndDate').val());
if (! moment(endDate, 'MM/DD/YYYY', true).isValid() ){
alert('Invalid Date');
} else {
eventData = {
title: $('#bookingName').val(),
start: new Date($('#createBookingModal .modal-header .modal-title span').text()),
end: endDate
};
$.ajax({
url: '/api/bookings/create',
data: {
title: eventData.title,
start_time: eventData.start,
end_time: eventData.end
},
success: function(response){
console.log(response);
// if ( response == 0 ){
// alert('Invalid Date');
// return false;
// } else {
// return true;
// }
}
});
$('#createBookingModal form').get(0).reset();
$("#createBookingModal").modal('hide');
$("#calendar").fullCalendar('renderEvent', eventData, true);
$('#calendar').fullCalendar('unselect');
}
}
});
HTML code
<div class="card-body full-calendar">
<div id='calendar'></div>
<!-- Display Create Booking form in modal -->
<div id="createBookingModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add an Booking on: <span class="startDate"></span>></h4>
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span> <span class="sr-only">close</span></button>
</div>
<div id="modalBody" class="modal-body">
<form>
<div class="form-group">
<label for="bookingName">Booking Title</label>
<input class="form-control" type="text" placeholder="Booking Name" id="bookingName">
</div>
<div class="form-group">
<label for="bookingEndDate">End Date</label>
<div class="input-group date" data-provide="datepicker">
<input type="text" id="bookingEndDate" class="form-control" placeholder="mm/dd/yyyy">
<div class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
</div>
<!--<div class="form-group">
<textarea class="form-control" type="text" rows="4" placeholder="Booking Description" id= "eventDescription"></textarea>
</div>-->
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button type="submit" class="btn btn-primary" id="submitButton">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Display Booking in modal -->
<div id="fullCalModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 id="modalTitle" class="modal-title"></h4>
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span> <span class="sr-only">close</span></button>
</div>
<div id="modalBody" class="modal-body">
<p class="start">Start At: <span></span></p>
<p class="end">End At: <span></span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<!-- <button class="btn btn-primary"><a id="eventUrl" target="_blank">Event Page</a></button>-->
</div>
</div>
</div>
</div>
I am not getting the end date for the newly created event when trying to display it in modal, you can notice //todo, that is where I want to get end date.May be it need to delegated, but I have no idea how it should be done?
I have added a fiddle here, you can see, the end date is coming "01-01-1970", because eventClick() is not getting the end date.
Update
It happens only when you are giving same start and end date.

I fixed it with just a small workaround, if anyone has a better solution, feel free to post.
eventClick: function(event, jsEvent, view) {
if ( event.end == null ){
event.end = event.start;
}
startDate = moment(new Date(event.start)).format("MM-DD-YYYY");
endDate = moment(new Date(event.end)).format("MM-DD-YYYY");
$('#modalTitle').text(event.title);
$('#modalBody .start span').text(startDate);
$('#modalBody .end span').text(endDate);
$('#fullCalModal').modal('show');
},
*#ADyson has a huge contribution on this solution, I was expecting to post this as an answer after our discussion, he did not post, so I am posting it.

I had a similar issue (about 2 years ago!) Had to use submitHandler: function(){} like below
submitHandler: function (form) {
var dataRow = CreateDataSetup();
$.ajax({
type: 'POST',
url: "/BookingTwo/SaveEvent",
data: dataRow,
success: function () {
$("#myform")[0].reset();
ClearPopupFormValues();
$('#popupEventForm').modal('hide');
},
statusCode: {
201: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("Success Event Created.", "success", 4000)
},
500: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("Internal Server Error - Logged with System Admins", "danger", 4000)
$('#popupEventForm').modal('hide');
},
400: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("Duration Service Returned 0 - Event NOT Created.", "danger", 4000)
$('#popupEventForm').modal('hide');
},
401: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("Warning - You do not have permission to delete this.", "danger", 4000)
$('#popupEventForm').modal('hide');
},
403: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("Warning - Can't delete approved events.", "danger", 4000)
},
409: function (response) {
$('#calendar').fullCalendar('refetchEvents');
ClearPopupFormValues();
showAlert("There is already an event for the user for this date.", "danger", 4000)
}
}
});
}
Also created a DataSetup funtion -
function CreateDataSetup() {
console.log("Attempting to Setup POST Values...")
var intEtad = parseInt($('#ETADType').val());
var intEtadSub = parseInt($('#ETADSubType').val());
var normStart = $('#LeaveStart').val();
var normEnd = $('#LeaveFinish').val();
var ahStart = $('#ADHOCLeaveStart').val();
var ahEnd = $('#ADHOCLeaveFinish').val();
var dataRow = {
'Id': $('#id').val(),
'Subject': $('#title').val(),
'Description': $('#customdescription').val(),
'StartTime': normStart,
'EndTime': normEnd,
'AHStartTime': ahStart,
'AHEndTime': ahEnd,
'SelectRole': $('#SelectRole').val(),
'ETADType': intEtad,
'ETADSubType': intEtadSub,
'StaffID': $('#StaffID').val(),
'EventStatus': $('#EventStatus').val(),
'AllRoles': $('#AllRoles').is(':checked'),
'AllDay': $('#AllDay').is(':checked'),
'AM': $('#AM').is(':checked'),
'PM': $('#PM').is(':checked'),
'ADHOC': $('#ADHOC').is(':checked'),
};
console.log("Setup Complete");
return dataRow;
}

Related

Modal not open when in normal window

Here I am using the croppie.js to upload an image for user. All are working perfectly but the problem is, the modal is only open when it is in debug window. When it is closed, the modal doesn't open.
Here is the HTML.
<div class="row">
<div class="col-md-12">
<div id="user_data">
</div>
</div>
</div>
<!-- crop image model -->
<div id="uploadimageModal" class="modal" 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">Upload & Crop Image</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-8 text-center">
<div id="image_demo" style="width:350px; margin-top:30px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<br />
<br />
<br />
<button class="btn btn-success crop_image">Crop & Upload Image</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Below is the Ajax query
load_data();
function load_data() {
$.ajax({
url: "adminquery/fetch/fetch.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
success: function (data) {
$('#user_data').html(data);
}
});
}
// crop image
$(document).ready(function () {
$image_crop = $('#image_demo').croppie({
enableExif: true,
viewport: {
width: 150,
height: 150,
type: 'square' //circle
},
boundary: {
width: 300,
height: 300
}
});
$('#upload_image').on('change', function () {
var reader = new FileReader();
reader.onload = function (event) {
$image_crop.croppie('bind', {
url: event.target.result
}).then(function () {
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
$('#uploadimageModal').modal('show');
});
$('.crop_image').click(function (event) {
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (response) {
$.ajax({
url: "profile/profilepic.php",
type: "POST",
data: { "image": response },
success: function (data) {
$('#uploadimageModal').modal('hide');
$('#uploaded_image').html(data);
load_data();
}
});
})
});
});
I am very grateful if someone help me. Thanks in advance.

Events not saving through my modal on FullCalendar (bs4)

I've been working on my own first independent project on fullcalendar, but I'm having issues adding and saving events through my modal. I've followed tutorials and code from similar issues but it's not working. Any ideas?
I want to be able to add events with the modal, pick the time and save the event.
Thanks in advance
$(document).ready(function() {
$('#calendar')
.fullCalendar({
allDaySlot: false,
customButtons: {
reload: {
text: '+1 Year',
click: function() {
$('#calendar').fullCalendar('gotoDate', new Date(new Date().setFullYear(new Date().getFullYear() + 1)));
}
}
},
themeSystem: 'bootstrap4',
defaultView: 'agendaWeek',
nowIndicator: true,
navLinks: true,
allDaySlot: true,
popupBreakPoint:786,
selectable: true,
selectHelper: true,
droppable: true,
slotDuration: '00:15:00',
selectOverlap: false,
editable: true,
disableResizing: false,
header: {
left: 'prev,next,today, reload, mnth',
center: 'title',
right: 'month,agendaWeek,agendaDay',
},
select: function(start, end) {
// Display the modal.
// You could fill in the start and end fields based on the parameters
$('.modal').modal('show');
},
eventClick: function(event, element) {
// Display the modal and set the values to the event values.
$('.modal').modal('show');
$('.modal').find('#title').val(event.title);
$('.modal').find('#starts-at').val(event.start);
$('.modal').find('#ends-at').val(event.end);
},
editable: true,
eventLimit: true // allow "more" link when too many events
});
// Bind the dates to datetimepicker.
// You should pass the options you need
$("#starts-at, #ends-at").datetimepicker();
// Whenever the user clicks on the "save" button om the dialog
$('#save-event').on('click', function() {
var title = $('#title').val();
if (title) {
var eventData = {
title: title,
start: $('#starts-at').val(),
end: $('#ends-at').val()
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
}
$('#calendar').fullCalendar('unselect');
// Clear modal inputs
$('.modal').find('input').val('');
// hide modal
$('.modal').modal('hide');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.min.css" />
<div id="calendar"></div>
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<form>
<div class="modal-body">
<div class="form-group">
<label for="company">Client Name</label>
<input type="text" class="form-control" id="title" placeholder="Clients name">
</div>
<div class="form-group">
<label for="vat">Starting time</label>
<input type="text" class="form-control" id="starts-at" placeholder="starts-at">
</div>
<div class="form-group">
<label for="street">Ending time</label>
<input type="text" class="form-control" id="ends-at" placeholder="ends-at">
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="save-event">Book</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>

fullcalnder not calls on button click and inside any function

I am using fullcalendar.
When my page loads fullcalendar loads properly.
Now, I want to retrieve new data from table and want to display it on calendar.
For that, I call an ajax on button click, The ajax will retrieve the new data from table and display on fullcalendar.
But i am getting an error in firebug console.
TypeError: $(...).fullCalendar is not a function
It works when page will load, but when i used it in a function or any click event it wont works.
Here is my code. Please check it and suggest me.
<script>
$(document).ready(function() {
var today = new Date();
// This works because it calls on page load
$('#calendars').fullCalendar({
header: {
right: 'month,agendaWeek,agendaDay,prev,next today'
},
defaultDate: today,
editable: true,
navLinks: true, // can click day/week names to navigate views
eventLimit: true, // allow "more" link when too many events
events: {
url: 'fullcalendar/demos/php/get-events.php',
error: function(eee) {
$('#script-warning').show();
}
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
// This doesn't works because it calls on button click. It gives me TypeError: $(...).fullCalendar is not a function
$("#clickme").click(function(){
var timezone = localStorage.getItem("timezone");
var start = "2016-10-16";
var end = "2016-10-21";
$('#calendars').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
url: "fullcalendar/demos/php/get-events.php?mode=customdate&start=" + start + "&end=" + end,
type: 'json',
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
});
});
</script>
<div id='script-warning'>
<code>php/get-events.php</code> must be running.
</div>
<div id='loading'>loading...</div>
<div>
<div class="row" style="border-top:2px solid">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" style="border-right:1px solid">
<div id='overviewDatePicker' style='margin-bottom:10px;margin-top:90px'></div>
<div><b>Filter By Eventname</b></div>
<div>
<input type="text" placeholder="Search"/>
</div>
<div><b>Filter By Stage</b></div>
<ul style="list-style:none">
<li><span class="glyphicon glyphicon-flag" style="margin:3px"></span>Tentative Booking</li>
<li><span class="glyphicon glyphicon-ok" style="margin:3px"></span>Complete Booking</li>
</ul>
<br><br><br>
</div>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8" id="eventcalendar">
<button id="clickme"> Click</button>
<div id="calendars"></div>
</div>
</div>
</div>
I have update my code according your code. Please check on click function where I have made changes modified you code accordingly and let me know outcome
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.0.1/fullcalendar.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.0.1/fullcalendar.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.0.1/fullcalendar.css" />
<script>
$(document).ready(function() {
var today = new Date();
// This works because it calls on page load
$('#calendars').fullCalendar({
header: {
right: 'month,agendaWeek,agendaDay,prev,next today'
},
defaultDate: today,
editable: true,
navLinks: true, // can click day/week names to navigate views
eventLimit: true, // allow "more" link when too many events
events: {
url: 'fullcalendar/demos/php/get-events.php',
error: function(eee) {
$('#script-warning').show();
}
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
// Please check this part only
$("#clickme").click(function(){
var timezone = localStorage.getItem("timezone");
var start = "2016-10-16";
var end = "2016-10-21";
$.ajax({
url: "fullcalendar/demos/php/get-events.php?mode=customdate&start=" + start + "&end=" + end,
type: 'json',
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
//$("#calendars").fullCalendar('removeEvents'); //If you want to remove existing events from calender
$("#calendars").fullCalendar('addEventSource', events);
}
});
});
});
</script>
</head>
<body>
<div id='script-warning'>
<code>php/get-events.php</code> must be running.
</div>
<div id='loading'>loading...</div>
<div>
<div class="row" style="border-top:2px solid">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" style="border-right:1px solid">
<div id='overviewDatePicker' style='margin-bottom:10px;margin-top:90px'></div>
<div><b>Filter By Eventname</b></div>
<div>
<input type="text" placeholder="Search"/>
</div>
<div><b>Filter By Stage</b></div>
<ul style="list-style:none">
<li><span class="glyphicon glyphicon-flag" style="margin:3px"></span>Tentative Booking</li>
<li><span class="glyphicon glyphicon-ok" style="margin:3px"></span>Complete Booking</li>
</ul>
<br><br><br>
</div>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8" id="eventcalendar">
<button id="clickme"> Click</button>
<div id="calendars"></div>
</div>
</div>
</div>
</body>
</html>

Modal Popup will not show if i do ajax-based paging inside my WebGrid

I am working on an asp.net mvc5 web application, and i am facing a problem as jquery is not loading if i do ajax paging inside my webgrid.
I got the following.The main view which have the grid:-
#model SkillManagement.Models.PagedList<SkillManagement.Models.Phone>
#{
ViewBag.Title = "Phone List";
}
<h1>Phone List</h1>
<div class="well">
#using (Html.BeginForm("index", null, FormMethod.Get))
{
<div style="margin-top:17px;">
#{
var grid = new WebGrid(
canPage: true,
rowsPerPage: Model.PageSize,
canSort: true,
ajaxUpdateContainerId: "grid");
grid.Bind(Model.Content, rowCount: Model.TotalRecords, autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
#grid.GetHtml(htmlAttributes: new { id = "grid" }, // id for ajaxUpdateContainerId parameter
fillEmptyRows: false,
tableStyle: "table table-bordered table-hover",
mode: WebGridPagerModes.All,
columns: grid.Columns(
grid.Column("PhoneId", "ID"),
//code goes here
grid.Column(header: "Action", canSort: false, style: "action",
format: #<text>
#Html.Raw("<a data-modal='' href='/phone/details/" + item.PhoneId + "' id='" + item.PhoneId + "' title='Detail'> <span class='glyphicon glyphicon-search'> </span> </a>")
#Html.Raw("<a data-modal='' href='/phone/edit/" + item.PhoneId + "' id='" + item.PhoneId + "' title='Edit'> <span class='glyphicon glyphicon-edit'> </span> </a>")
#Html.Raw("<a data-modal='' href='/phone/delete/" + item.PhoneId + "' id='" + item.PhoneId + "' title='Delete'> <span class='glyphicon glyphicon-trash'> </span> </a>")
</text>)
));
}
</div>
}
</div>
<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
#section scripts{
#Scripts.Render("~/scripts/appjs/phones.js")
}
and the _partial view which will be rendered as a modal popup:-
#model SkillManagementTDMGroup.Models.Phone
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Edit Phone</h3>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m=>m.PhoneId)
<div class="modal-body">
//code goes here...
<input class="btn btn-primary" type="submit" value="Save" />
<button class="btn btn-warning" data-dismiss="modal">Close</button>
</div>
}
<script>
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
</script>
and here is the phones.js:-
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
var isValid = true; // assume all OK
$('form').validate(); // perform validation on the form
$('input[type="text"]').each(function (index, item) { // could change selector to suit e.g $('input, textarea').each(..
if (!$(this).valid()) {
isValid = false; // signal errors
return false; // break out of loop
}
})
if (!isValid) {
return false; // exit
}
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
//location.reload();
alert(result.message);
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
now when i visit the main view the modal popup will work well, but if i do some paging inside the webgrid and i click to render the partial view as modal popup i will get the following exception :-
Unhandled exception at line 51, column 9 in http://localhost:58652/phone/edit/3
0x800a1391 - JavaScript runtime error: '$' is undefined
on the following Script section inside the partial view:-
<script>
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
</script>
This issue is fixed and worked fine for me....
"Modal Popup will not show if i do ajax-based paging inside my WebGrid"
OR
"When navigate to 2nd page and click on edit, delete or view it is displaying normal page instead of displaying it in modal pop up".
Change code in phones.js:
From
$("a[data-modal]").on("click", function (e) {
To
$(document).on("click","a[data-modal]", function (e) {
Enjoy coding................

Jquery function not called when called on modal pop up submit button in partial view in ASP.net MVC

I want to call jquery function on Modal popup submit button, which is in partial view but the function is not called if that button is in partial view, it is only called when i put my modal pop up in main view. How to solve this issue... Please help .. Thanks
Index.cshtml
#Html.ActionLink("Create", "Create", null, null, new { id = "btnCreate", #class = "btn btn-small btn-info" })
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
$('#btnCreate').click(function () {
alert("function called");
$('.modal-dialog').load(this.href, function () {
$('#ShowModalDialog').modal({
backdrop: 'static',
keyboard: true
}, 'show');
});
return false;
});
});
</script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$('#Useremail').blur(function () {
alert("func called");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Search',
data: "{'searchString':'" + document.getElementById('Useremail').value + "'}",
async: false,
success: function (response) {
alert("Record found");
},
error: function () { alert("record not found"); }
});
});
});
</script>
<div id='ShowModalDialog' class='modal fade in'>
<div class='modal-dialog'>
</div>
</div>
</body>
</html>
_Create.cshtml PartialView
#model MvcTwitterBootstrap.Models.UserDetail
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×</button>
<h3 id="myModalLabel">
Registration</h3>
</div>
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { #class = "modal-form" }))
{
#Html.ValidationSummary()
<div class="modal-body">
<div>
#Html.LabelFor(x => x.UserEmail)
#Html.TextBoxFor(x => x.UserEmail, new { #id = "Useremail" })
#Html.ValidationMessageFor(x => x.UserEmail)
</div>
<div>
#Html.LabelFor(x => x.UserPassword)
#Html.TextBoxFor(x => x.UserPassword, new { id = "Userpassword" })
#Html.ValidationMessageFor(x => x.UserPassword)
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">
Cancel</button>
<button class="btn btn-primary" type="button" id="btnsubmit">
Save</button>
</div>
}
</div>
for items that are added to the form after load you need to put the function on the document instead of the item
$(document).on('click', '#btnCreate', function(){
//code
});
the other option would be to put all of the click events in a function
function LoadScript(){
//jquery code here
}
and then call that function after the partial is loaded
$('#divContent').html(result);
LoadScript();

Categories

Resources