Popup containing selectable items, submit to update partial view - javascript

I am trying to create a map page where the user can select multiple items to display on the map. I already got the map working with google maps javascript api but it only shows one item at a time based on the id in the url.
I am open to suggestions, but I am thinking the user should be able to open a popup or combobox which contains a list of items. Multiple items can be selected and when the user clicks ok, the selected items are passed into a partial view containing the map.
Any help will be greatly appreciated, thanks in advance!!
Here are some bits of code from other parts of the site that might be helpful. I modified some of it to make sense in this context so I'm sorry if it's sloppy.
Popup window, could use this or some sort of combobox:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
data-backdrop="static" data-keyboard="false" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Select Assets</h4>
</div>
<div class="modal-body">
<form>
<input type="checkbox" id="select_all" /> All Assets
#{ List<string> usedNodes = new List<string>(); }
#foreach (var run in Model.Runs)
{
if (!usedNodes.Contains(run.NodeID))
{
if (run.GPS_Lattitude != zero && run.GPS_Longitude != zero)
{
<input type="checkbox" /> #run.NodeID
}
usedNodes.Add(run.NodeID);
}
}
</form>
</div>
<div class="modal-footer">
<button id="cancel" type="button" class="btn btn-primary">Cancel</button>
<button id="ok" type="button" class="btn btn-primary">Ok</button>
</div>
</div>
</div>
Popup script:
window.onload = function () {
getMapMarkers();
$('#cancel').on('click', function (e) {
$('#myModal').modal('hide');
});
$('#ok').on('click', function (e) {
$('#myModal').modal('hide');
getMapMarkers();
});
}
function getMapMarkers() {
$.ajax({
url: '#Url.Action("GetMarkers", "Map")',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: { nodename: node, servername: server },
success: function (???) {
???
}
});
}
Partial view change script, working great for selecting one item from a dropdown, but now I need to be able to select multiple items:
$('#assetSelect').change(function () {
var assetId = $(this).val();
$.ajax({
type: 'GET',
url: "#Url.Action("MapData", "Map")",
data: {
Id: assetId
},
success: function (result) {
$('#partialMap').html(result);
$('#partialMap').fadeIn('fast');
}
});
});
Script for the select all checkbox seen in the popup window, does what it's supposed to, but it needs to become unchecked when you uncheck any other item:
$('#select_all').click(function () {
var c = this.checked;
$(':checkbox').prop('checked', c);
});
Thanks again!

Related

Laravel How to reset modal ajax data values upon closing the modal

I am currently working on populating a user's searching for available appointments by selecting a date, start time and end time. I am trying to populate them onto a modal which is currently working. However I realise that whenever I close the modal and search for the new timeslots, the previous data populated on the modal will still be there.
I have tried doing function when I close the modal, the modal data will be cleared.
Below are my html codes for the modal:
<div class="modal fade" id="myModalNewAppointment">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Select Appointment</h4>
</div>
<!-- Modal body -->
<div class="modal-body">
{{-- <form id="test" action="" method="post"> --}}
<div class="form-group">
<label for="modal">Select a Timeslot</label>
<div class="spacer"></div>
<div class="timeslots-section">
<div class="timeslots text-center">
</div> <!-- end timeslots -->
</div>
</div>
{{-- </form> --}}
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="new_appt_cfm_btn" data-loading-text="<i class='fa fa-spinner fa-spin'></i> saving..">Confirm</button>
<button type="button" class="btn btn-outline-primary" id="close_btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Below is my ajax method to retrieve the timeslots:
$("#find_appointment_btn").click(function(event){
event.preventDefault();
let select_date = $('#select_date').val();
let start_time = $('#start_time').val();
let end_time = $('#end_time').val();
let data = { select_date: select_date, start_time: start_time, end_time: end_time };
$.ajax({
type:"POST",
url: "{{ route('assistant.newappts.get') }}",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
dataType: "json",
success:function(data){
console.log(data);
if(data == ""){
alert("Clinic is close!");
return;
}
else if(data != ""){
$('#myModalNewAppointment').modal({backdrop: 'static', keyboard: false});
data.forEach(function(dt) {
// do something with `item`
// $(".timeslots").append(dt);
$('.timeslots').append('<input type="checkbox" class="timeslotchk" name="timeslot" value="'+ dt +'"/>' + dt );
});
}
},
error: function(error) {
console.log(error);
}
});
});
Below is the method I have tried to reset the data populated on my modal:
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').reset();
});
When you call the ajax request on the success you have appended the data in model "timeslots" division so its obvious that data will be still there on the hiding model try to empty the timeslots, try below code hope it work for you and make sure that method trigger on closing of model
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').find(".timeslots").empty();
});

How to pass a parameter to a modal form using Ajax

I have a razor page that displays a list of expenses for the Report selected. I have an "Add Expense" button on the page that brings up a modal. The modal is a partial View of the form. What i need to do is pass the ExpenseId to the modal. I can get the Id from the url like this
#{ var expenseId = Request.Url.Segments[3]; }
the button currently looks like this
<button type="button" data-toggle="modal" data-target="#expenseModal_#expenseId" data-id="#expenseId" class="btn btn-primary" id="addExpenses">
Add Expense
</button>
There are a few things in this that i do not know if i even need them. I was trying different things.
Modal
<!-- MODAL -->
<div class="modal fade" id="expenseModal_#expenseId" tabindex="-1" role="dialog" aria-labelledby="expenseModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="expenseModalLabel"> Expences </h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div> <!-- MODEL HEADER-->
<div class="modal-body">
</div> <!-- MODAL BODY-->
</div>
</div>
Javascript
<script type="text/javascript">
$(document).ready(function () {
$("#addExpenses").click(function () {
$(".modal-body").html('');
$.ajax({
type: 'GET',
url: '#Url.Action("_ExpenseForm", "Admin")',
data: { type: $(this).attr("data-type") },
success: function (response) {
$(".modal-body").html(response);
$("#expenseModal").modal('show');
},
error: function () {
alert("Something went wrong");
}
});
});
});
</script>
The expense Id has to be inserted in the form so that when it is saved it saves it to the correct Expense report.
Controller actions
ExpensesDataAcessLayer objexpense = new ExpensesDataAcessLayer();
public ActionResult ExpenseReports()
{
return View(db.ExpenseReports.ToList());
}
public ActionResult Expenses(int ExpenseId)
{
return View(db.Expenses.Where(x => x.ExpenseId == ExpenseId).ToList());
}
public ActionResult _ExpenseForm()
{
CustomerEntities customerEntities = new CustomerEntities();
List<SelectListItem> categoryItem = new List<SelectListItem>();
ExpensesViewModel casModel = new ExpensesViewModel();
List<ExpenseTypes> expensetypes = customerEntities.ExpenseType.ToList();
expensetypes.ForEach(x =>
{
categoryItem.Add(new SelectListItem { Text = x.CategoryItem, Value = x.ItemCategoryId.ToString() });
});
casModel.ExpenseTypes = categoryItem;
return View(casModel);
}
Thanks for your help!
You can store expenseId into hidden field, like this
<input id="expenseId" name="expenseId" type="hidden" value="#Request.Url.Segments[3]">
Then you can get like this
$("#addExpenses").click(function () {
var expenseId = $("#expenseId").val();
// after code here
Updated
You can get expenseId like this
var expenseId = $(this).attr("data-id")
Then you can assign it to hidden field or anywhere in Model, Like this
<!-adding aditional input into HTML in MODEL-!>
<input id="expenseId" name="expenseId" type="hidden" value="">
<!- Javascript-!>
var expenseId = $(this).attr("data-id")
expenseId.val(expenseId );

Pass Data from HTML Table to Modal and then to PHP script

I have a index.php in which i have a Table with data from a MySQL database. Each row in the table has the data for the corresponding data in my database. Each row has a delete button. I want to show up a Modal and ask for permission to delete the entry. If the accepting Button is pressed i want to pass the id of that row to a delete.php script where the deletion is handled. So how do i pass the id for a row from my table to the modal and then to my delete.php. I know that i need jquery and ajax for it but im a total beginner with them. Im using bootstrap.
this is my button:
<a class="btn btn-danger" href="#delModal" data-toggle="modal
data-row-id="<?php echo $row['id'];?>" " >Delete</a>
and my modal:
<div class="modal" id="deleteModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Delete Entry</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<input type="hidden" name="id" value=""/>
<div class="modal-body">
<p>Are you sure that you want to delete the selected Entry? There is no way to restore the deleted data!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="accDelBtn">Yes, delete.</button>
<button type="button" class="btn btn-danger" id="disMdBtn" data-
dismiss="modal">No, abort.</button>
</div>
</div>
my jquery/ajax garbage try:
<script type="text/javascript">
$('#delBtn').on('click', function() {
$('#deleteModal').show();
});
$('#disMdBtn').on('click', function(){
$('#deleteModal').hide();
});
$('#accDelBtn').click(function() {
$.ajax({
type: "POST",
url: "delete.php",
data: { id: $row['id'] }
})
});
</script>
Any help is appreciated!
I added an attribute for each ‍button tag called record_id and the record ID should be stored in it.
for example :
<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="delBtn" record_id="1">
<span aria-hidden="true">×</span>
</button>
And when the button ('#delBtn') is clicked, I get the ID and save the variable.
<script type="text/javascript">
var id = null
$('#delBtn').on('click', function() {
id=$("#delBtn").attr("record_id")
$('#deleteModal').show();
});
$('#disMdBtn').on('click', function(){
$('#deleteModal').hide();
});
$('#accDelBtn').click(function() {
$.ajax({
type: "POST",
url: "delete.php",
data: { id: id }
})
});
</script>
And when I click on the button ('#accDelBtn'), I will send it.
You need to store the id of the row globally. Add a variable at the beginning of your script:
var rowToDelete = null;
Then, when you click a delete button, update it in the click handler:
rowToDelete = ID_TO_DELETE;
Finally, you can transmit it as:
data: { id: rowToDelete }
})
});
You have placed an hidden field with name attribute as "id", which you can use for doing further actions.
Check below code:
<script type="text/javascript">
$('#delBtn').on('click', function() {
$('#deleteModal').show();
// setting value of hidden input field by using currently clicked link data-row-id attribute
$('#deleteModal').find('input[name="id"]').val($(this).attr('data-row-id'));
});
$('#disMdBtn').on('click', function(){
$('#deleteModal').hide();
});
$('#accDelBtn').click(function() {
// retrieving value of hidden input field
var id = $('#deleteModal').find('input[name="id"]').val();
$.ajax({
type: "POST",
url: "delete.php",
data: { id: id }
});
});
</script>
I have just setted value of hidden field, on anchor tag click. And retrieving that hidden field value when doing ajax call.

Google Maps autocomplete in Bootstrap modal with Vue.js

I have Boostrap modal with <input>. I have implemented Google autocomplete for it with the following well-known trick:
.pac-container {
z-index: 10000 !important;
}
Now I'm struggling to make autocomplete working inside 2nd layer Boostrap Modal. Unfortunately, the z-index trick doesn't work here.
<div class="modal fade" id="editItemModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div id="editItem" class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Update Address <b>{{selectedItem.properties.NAME}}</b>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label class="sr-only" for="editItem_ADRESS1"></label>
<input v-model="selectedItem.properties.ADRESS1" type="text" class="form-control" id="editItem_ADRESS1" ref="editItem_ADRESS1" placeholder="{{selectedItem.properties.ADRESS1}}">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-success btn-ok" #click="save_item()" data-dismiss="modal">Save</a>
</div>
</div>
</div>
</div>
Then comes the Vue object
const editItem = new Vue({
el: "#editItem",
data: {
items: null,
selectedItem: null,
},
methods: {
save_item() {
this.selectedItem = itemsList.selectedItem;
var ip = location.host;
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://' + ip + '/updateItem',
data: {
command: "edit_item",
item_id: this.selectedItem.id,
adress1: this.selectedItem.properties.ADRESS1
},
success: function (responseData) {
if (responseData.result === false) {
console.log(responseData.result);
}
else {
console.log("successfully updated");
}
},
error: function (error) {
console.log('error', error);
}
}); // end of ajax
} // end od save_item()
} // end of methods
});
Finally, I was able to figure out what was the issue. It turns out that the DOM object is not created yet by Vue when the Google iniAutocomplete() function sets listeners.
In addition, my <input> didn't run the Google geolocate() function. That's how the <input> looks now:
<div class="form-group">
<label class="sr-only" for="edit-item_ADRESS1"></label>
<input id="edit-item_ADRESS1" v-model="selectedItem.properties.ADRESS1" type="text" class="form-control" onFocus="geolocate('edit-item')">
</div>
The next step was to make a minor change in the geolocate() function. I pass action variable onFocus event and use it to determine what DOM object initiated the call.
if (action == "add-item") {
autocomplete_add_item.setBounds(circle.getBounds());
}
if (action == "edit-item") {
// we need to run iniAutocomplete again after the DOM object was finally created by Vue
initAutocomplete();
autocomplete_edit_item.setBounds(circle.getBounds());
}

Open and Load Modal Window w/ Javascript and Codeigniter

I'm using Codeigniter and Datatables together and need to load a modal popup when the user clicks "view" for a certain row of data.
Here is my link with my onClick:
view
Here is my JS:
function notes_modal(data) {
$.ajax({
type: "POST",
url: "../load_notes_modal",
}).done(function ( html ) {
$("#selected_note").modal('show');
});
}
Here is my view that is being loaded by the "load_notes_modal" function I'm calling:
<div class="modal fade" id="selected_note" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog">
<div class="modal-content">
Random Content!
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">View Location Note</h4>
</div>
<div class="modal-body"></div>
</div>
</div>
I'm not getting any errors, just no luck getting the modal to show. I'm new to JS and trying to learn, I might be headed in the complete wrong direction!
You will want to put your modal trigger in the success callback like so:
HTML
view
JS
function notes_modal() {
$.ajax({
type: "POST",
url: "../load_notes_modal",
success: function ( html ) {
$("#selected_note").modal('show');
},
error: function() {
alert('ajax did not succeed');
}
});
}
function clickListener() {
$('.openModal').unbind();
$('.openModal').click(function (e) {
e.preventDefault();
notes_modal();
});
}
You have your dataTable something like below. Call the functions from within fnDrawCallback() so that each time the table is drawn, the listeners are called. Note the changes made above as well.
var oTable = $('#myTable').dataTable({
"fnDrawCallback": function (oSettings) {
notes_modal();
clickListener();
}
});
New Update: To work with dataTable redraw.

Categories

Resources