How would i edit/update values in a dynamic table using jQuery? - javascript

I have a program that accepts inputs from a user by entering them into a modal, after doing so, the user clicks a button which adds all the inputs to their respective columns within the tables row. The user is allowed to add as many rows as they need with varying information. The inputs are as follows: An image via an input of type file, as well as two text inputs, one for their name and another for their surname.
Alongside the inputs displayed within the row, i have created an edit and delete button. The focus for this question will be on the edit button. Once pressed, the edit button needs to bring up an update modal with the same fields as the original adding modal. The user should be able to change/update the information within all 3 inputs, and this should dynamically update the row for which the edit button had been pressed (each row has its own edit button).
How would i go about doing this? My jQuery code is as follows:
//add data
$("#addToTable").click(function() {
var imageLocation = $("#insertImage").val().replace(/C:\\fakepath\\/i, "images/");
counter++;
$("#container table").append(
$('<tr id="' + counter + '">')
//below is the image input
.append($('<td class="align-middle">').html("<img src=" + imageLocation + " class='image' data-toggle='popover'" + "data-img=" + imageLocation + ">").on("mouseover", function() {
$('[data-toggle="popover"]').popover({
trigger: 'hover',
html: true,
content: function() {
return '<img class="img-fluid" src="' + $(this).data('img') + '" />';
},
title: 'Enlarged Image'
})
}))
.append($('<td class="align-middle">').html($('#addName').val())) //the name input
.append($('<td class="align-middle">').html($('#addSurname').val())) //the surname input
.append($('<td class="align-middle">').html("<i class='fas fa-user-edit faa-shake animated-hover' id='pencilIcon'></i></button>").on("click", function() {
$('#updateDataOnTable').modal("toggle"); // this brings up the update modal once the edit button has been pressed.
}))
.append($('<td class="align-middle">').html("<i class='fas fa-dumpster faa-shake animated-hover' id='dumpsterIcon'></i>").on("click", function() {
let deleteRow = this;
$('#modalDelete').modal("toggle");
$('#no').on("click", function() {
$('#modalDelete').modal("toggle");
deleteRow = "";
})
$('#yes').on("click", function() {
$(deleteRow).parents("tr").remove();
$('#modalDelete').modal("toggle");
})
}))
)
formClear(); //clears the inputs
});
As it stands, the program only brings up the update modal (HTML code shown below):
<!-- Update Modal -->
<div class="modal fade" id="updateDataOnTable" tabindex="-1" role="dialog" aria-labelledby="website" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Update Table</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="" action="index.html" method="post">
<form>
<div class="form-group">
<label for="updateImage">Insert Image</label>
<input type="file" class="form-control-file" data-toggle="popover" data-html="true" data-placement="bottom" name="insertImage" id="updateImage" accept="image/x-png,image/gif,image/jpeg" aria-describedby="inputHelp">
</div>
<div class="form-group">
<label for="updateName">Name</label>
<input type="text" class="form-control" id="updateName">
</div>
<div class="form-group">
<label for="updateSurname">Surname</label>
<input type="text" class="form-control" id="updateSurname">
</div>
</form>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="updateTable" value=id>Update</button>
</div>
</div>
</div>
</div>
Any help would be greatly appreciated! :)

Related

Razor Return Page to a specific location in Post Method

So idea is Id like the user to click a button, have the page submit through the post method which will populate fields for a form, then return the page with a modal displayed. I have this working, except the issue is that the page is at the top even if the user clicked halfway down. Id like the page to redisplay where it was, with the modal displaying.
I know that there is a fragment parameter, but only for redirecttopage and not page()? Sending it back to get resets everything, so thats not realy ideal. Ive also tried altering the url with javascript which works with setting the page position, but somehow it will not display the modal with that?
Does anyone know how to easily return the page in the post method to a specific spot on the page?
Javascript: (Modal shows up for one second then disappers when it goes to the page position)
function OnLoad() { //Used for redisplaying on error purposes
if ("#TempData["EditingParty"]" == "Yes") {
var loadedURL = window.location.href;
var fragmentPieceOfURL = "#TempData["EndOfURL"]"
location.href = loadedURL + fragmentPieceOfURL;
document.getElementById("EditUsersForm").style.display = "inline-block";
}
else {
document.getElementById("EditUsersForm").style.display = "none";
}
}
Cshtml
Button that goes to post (i is counter to keep track of anchor tag for redisplay location):
<a id="#i"></a>
<button type="submit" style="white-space:nowrap" class="btn btn-secondary btn-sm" formnovalidate asp-page-handler="DisplayEdit" asp-route-id="#Model.UsersOnCaseList.ElementAtOrDefault(i).UserID" asp-route-AttorneyRole="#Model.UsersOnCaseList.ElementAtOrDefault(i).AttorneyRole" asp-route-email="#Model.UsersOnCaseList.ElementAtOrDefault(i).EmailAddress" asp-route-pAttorneyRoleID="#Model.UsersOnCaseList.ElementAtOrDefault(i).AttorneyRoleID" asp-route-PageFragment="#i" asp-route-pEditAttorneyUserID="#Model.UsersOnCaseList.ElementAtOrDefault(i).UserID">Edit <i class="fas fa-ribbon"></i></button>
Modal:
<div class="modal" tabindex="-1" role="dialog" id="EditUsersForm" style="display:none">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit User</h5>
<button type="button" onclick="closeEditUsersForm()" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="form-group" style="margin-top:15px;padding-left:15px">
<label asp-for="EditUserEmailInput"></label> <span class="red">*</span>
<input asp-for="EditUserEmailInput" class="form-control" id="EmailInputBox" value="#Model.EditUserEmailInput" style="display:block;width:25em" />
<span style="display:block" asp-validation-for="EditUserEmailInput" class="text-danger" id="AddUserInputValidation"></span>
</div>
<div class="form-group" style="margin-top:15px;padding-left:15px">
<label class="control-label">Role</label> <span class="red">*</span>
<select asp-for="AttorneyRoleIDEditForm" asp-items="#(new SelectList(Model.AttorneyRolesList, "AttorneyRoleID","AttorneyRole"))" name="AttorneyRoleIDEditForm" id="SelectAttorneyRoleIDEditForm" class="form-control" style="width:25em" onchange="DidSelectPlaintiffEdit()">
<option class="form-control" value=-1>Select a Role</option>
</select>
<span asp-validation-for="AttorneyRoleIDEditForm" class="text-danger"></span>
</div>
<div class="form-group" style="margin-top:15px;padding-left:15px">
<label asp-for="EditUserPartyInput"></label> <span class="red">*</span><br />
<input asp-for="EditUserPartyInput" value="#Model.EditUserPartyInput" class="form-control" id="PartyNameInputEdit" style="display:inline-block;width:25em" />
<span style="display:block" asp-validation-for="EditUserPartyInput" class="text-danger" id="PartyNameInputValidation"></span>
</div>
<div class="modal-footer">
<button class="btn btn-primary" style="margin:0 auto" asp-page-handler="SaveUserEdits" asp-route-UserBeingEdited="" id="EditSubmitButton" name="EditUserSubmit" value="Yes">Submit</button>
<button class="btn btn-primary" style="margin:0 auto; display:none" asp-page-handler="SaveUserEdits" disabled id="SubmitButtonDisabled" name="AddUserSubmit" value="Yes">Submit</button>
</div>
</div>
</div>
</div>
CS file:
public IActionResult OnPostDisplayEdit(int id, string email,string AttorneyRole,int pAttorneyRoleID,int pAttorney,int pEditAttorneyUserID,int PageFragment)
{
EditUserEmailInput = email;
string curDictionaryAttorneyRole;
if (AttorneyRole.Contains('('))//Just because in development user didnt always have ability to enter a party
{
curDictionaryAttorneyRole = AttorneyRole.Split(new[] { '(' }, 2)[0].Trim();
EditUserPartyInput = AttorneyRole.Split(new[] { '(' }, 2)[1];
var LastRightParenIndex = EditUserPartyInput.LastIndexOf(')');
EditUserPartyInput = EditUserPartyInput.Substring(0, LastRightParenIndex); //Pulling the right parenthesis out
}
else //Its just the dictionary role
{
curDictionaryAttorneyRole = AttorneyRole;
EditUserPartyInput = null;
}
TempData["EditingParty"] = "Yes";
TempData["EndOfURL"] = PageFragment.ToString() + "&#" + PageFragment.ToString();
SetFileSequenceField();
ModelState.Clear(); //Used to remove the validations
SetAttorneyRoleList();
var selectedIndex = AttorneyRolesList.Where(arl => arl.AttorneyRole == curDictionaryAttorneyRole).Select(arl => arl.AttorneyRoleID).FirstOrDefault();
AttorneyRoleIDEditForm = selectedIndex;
EditAttorneyUserID = pEditAttorneyUserID;
UneditedEmail = email;
UneditedAttorneyRoleID = pAttorneyRoleID;
PopulateUserList();
//return RedirectToPage("AddUsersToCase","GET",fragment:PageFragment.ToString());
return Page();
//var PageURL = Page();
//PageURL = PageURL. + "&#" + PageFragment.ToString();
//return PageURL;
}
You can try to replace
location.href = loadedURL + fragmentPieceOfURL;
to
history.pushState({}, null, loadedURL + fragmentPieceOfURL);
So that the page will not be refreshed with location.href.

Prevent Hidden Bootstrap 4 Modals to react events

I am trying to create a "Confirmation Modal" on deleting a row in a table. When the user wants to delete a row a Modal is shown (on click of a button) in which the user must type the username as a confirmation to delete it and click the delete button. This table have multiple rows (one for each user) and every row has its own "delete button" created with this loop:
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
?>
<tr>
<th scope="row"><?=$row["ID"]?></th>
<td><?=$row["username"]?></td>
<td><?=$row["mail"]?></td>
<td><button class="btn btn-sm btn-primary"><i class="fas fa-pencil-alt"></i></button></td>
<td><button class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#delete-user-modal" data-bs-user-id="<?=$row["ID"]?>" data-bs-username="<?=$row["username"]?>"><i class="fas fa-trash"></i></button></td>
</tr>
<?php
}
This is how i set my modal:
<!--DELETE USER MODAL-->
<div class="modal modal-dialog modal-dialog-centered fade" id="delete-user-modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p></p>
<input type="text" name="username" class="form-control" id="username-input">
<input hidden type="text" name="user_id">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" id="modal-delete-button" class="btn btn-danger disabled" >Elimina</button>
</div>
</div>
</div>
</div>
Via data-bs I pass the ID and username for each button and I put these data in the Modal with:
$("#delete-user-modal").on('show.bs.modal', function (event) {
// Button that triggered the modal
var button = event.relatedTarget
// Extract info from data-bs-* attributes
var userId = button.getAttribute('data-bs-user-id')
var username = button.getAttribute('data-bs-username')
// Update the modal's content.
var modalTitle = $(this).find('.modal-title')
var modalP = $(this).find('.modal-body > p')
var modalInput = $(this).find('.modal-body > input')
var modalDeleteBtn = $(this).find('#modal-delete-button')
modalTitle.append('Vuoi eliminare <span class="bold">' + username + '</span>?')
modalP.append('Scrivi <span class="bold">' + username + '</span> per confermare')
$("#delete-user-modal").on('keyup', event => {
console.log(modalInput.val())
if(modalInput.val() === username){
console.log("check")
//modalDeleteBtn.classList.remove('disable')
}
})
})
The problem is that when I close a modal and open a new one (ie: clicking button of another row) also the one that is hide react to the on('keyup') event.
I need a way to open a fresh Modal every time i click a new button or reset the modal that I close and have the new one completely fresh.
This for me resolved with:
$("#delete-user-modal").on('hidden.bs.modal', function (event) {
$(this).unbind('keyup')
});

Laravel modal hidden value to call route

I have a modal with a hidden field of my current id that I need.
I need to click a button in my modal to confirm if I should delete a user. I setup a form not sure if this is the best option and in javascript set the attr of form to the route but the route isn’t finding the correct path although in the URL it says it correctly what am I missing maybe the route should be in PHP instead of JS?
<div class="modal" id="mdelete" role="dialog" aria-labelledby="moddelete">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="moddelete">Confirm Delete</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete</p>
</div>
<div class="modal-footer">
<form method="POST" id="formdelete">
<input type="hidden" name="txtid" id="txtid" />
<input type="text" name="uid" id="uid" />
<button type="button" class="btn btn-danger " data-dismiss="modal">No</button>
<span class="text-right">
<button type="submit" class="btn btn-primary btndelete">Yes</button>
</span>
</form>
</div>
</div>
Show
Edit
<button type="button" class="btn btn-danger ml-2" data-toggle="modal"
data-target="#mdelete" data-id="{{$user->id}}"
data-name="{{$user->username}}">Delete</button>
$(document).ready(function() {
$('#mdelete').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var userid = button.data('id');
var uname = button.data('name');
var modal = $(this);
modal.find('#txtid').val(userid);
modal.find('#uid').val(userid);
modal.find('.modal-body').text('Are you sure you want to delete ' + uname);
})
$('#formdelete').submit(function() {
var userid = $('#txtid').val();
$('#formdelete').attr("action", "route('$users.destroy',$user->"+ userid +")");
$('#formdelete').submit();
});
});
Your attempt to generate route will fail because you are not using templating correctly:
$('#formdelete').attr("action", "route('$users.destroy',$user->"+ userid +")");
You can try to have your route accept optional user field, and then generate route to it, and with js append user ID value something like so:
<script>
$(function() {
var form = $('#formdelete');
var path = '{{ route("users.destroy") }}';
$('#formdelete').submit(function(event) {
var form = $(this);
var userid = form.find('#txtid').val();
$('#formdelete').attr("action", path + '/' + userid);
$('#formdelete').submit();
});
});
</script>

How to make a Javascript button onclick() call a function that opens a bootstrap modal with an Ajax request?

I am trying to make a bootstrap 4 modal that opens when a button is pressed inside a dynamically created element which makes an Ajax request to a form pre-populated with the data from the associated id, and then a button to save the updated information into the database.
Currently, the edit button opens a new page "editData" with the prepopulated data associated with the passed id, which then can be used to update the information upon pressing a button, and then returns to the previous page.
What are the methods that I can use to make the button open a modal on the current page that can provide the same function?
function populateData(dataInput) {
var row = $('<tr id=' + dataInput.id + '/>');
$('#table').append(row);
row.append($('<td>' + dataInput.name + '</td>'));
row.append($('<td>' + dataInput.description + '</td>'));
row.append($(
'<td><input type="submit" class="btn btn-warning" value="edit" onclick="edit(' +
dataInput.id + ')"/>'));
}
function edit(id) {
$.ajax({
type: 'GET',
url: '/getData?id=' + id,
success: function(data) {
var dataInput = JSON.parse(data)[0];
window.location = '/editData?id=' + dataInput.id;
}
})
}
Here is the getData that dynamically populates the table
app.get('/getData', function(req, res) {
var content = {};
mysql.pool.query('SELECT * FROM dataTable WHERE id=?', [req.query.id],
function(err, rows, fields) {
if (err) {
next(err);
return;
}
content.results = JSON.stringify(rows);
res.send(content.results);
});
});
And here is the editData.handler content
<div>
<form id="form">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="">
<label for="description">Description:</label>
<textarea id="description" name="description" rows="4" cols="50"></textarea>
</form>
<div class="centerButton">
<input id="submit" class="btn btn-primary" type="submit" value="Save" onclick="save()" />
</div>
</div>
This is a simple bootstrap modal.
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Now JavaScript part to make ajax request and embed data into modal.
function populateData(dataInput) {
var row = $('<tr id=' + dataInput.id + '/>');
$('#table').append(row);
row.append($('<td>' + dataInput.name + '</td>'));
row.append($('<td>' + dataInput.description + '</td>'));
//check that I have added attributes data-toggle and data-target to point example modal
row.append($(
'<td><input type="submit" data-toggle="modal" data-target="#exampleModal" class="btn btn-warning" value="edit" onclick="edit(' +
dataInput.id + ')"/>'));
}
function edit(id) {
$.ajax({
type: 'GET',
url: '/getData?id=' + id,
success: function(data) {
var dataInput = JSON.parse(data)[0];
//commented following line and adding code to embed data into modal
//window.location = '/editData?id=' + dataInput.id;
$('.modal-body').html('html that you want to show');
}
})
}
It works and here is a demo on Codepen.
Please make sure that you have include bootstrap and jquery.

Summernote tooltips not appearing in a bootstrap Modal window

I am trying to implement the Summernote WYSIWYG editor in a bootstrap modal window. The problem I am getting is that the tooltips on hover do not appear when I do this in a modal. (works fine without modal). What appears to happen is sometimes you can see just behind the modal window there is the edge of the tooltip border, making me think that they are behind the window. I tried targeting the tooltip and changing its Z-index to 9999 but that did not work. Please could you help me figure out where I am going wrong.
<!--################### Bootstrap Modals With Forms DESCRIPTION ##########################-->
<!-- <button class="btn-u" data-toggle="modal" data-target="#responsive">Launch Button</button> -->
<div class="modal fade sky-form blackform" data-backdrop="static" id="descriptionform" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content col-md-12" style="min-width:490px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Project Description</h4>
</div>
<div class="modal-body" >
<div class="row">
<!-- <div class="modal-body"> -->
<!-- ################CONTENT FOR MODAL#################### -->
<div class="col-lg-12">
<form action="PR_detailsform.php" method="post" id="projdescription">
<input type="hidden" name="idkey" value="<?php echo $Pkey; ?>">
<input type="hidden" name="catx" value="<?php echo $cat; ?>">
<input type="hidden" name="navx" value="<?php echo $nav; ?>">
<div class="form-group">
<label for="">Edit</label>
<textarea name="details" id="summernote" rows="10" class="form-control"><?php echo $projectdetail; ?></textarea>
</div>
<button style="background:#72c02c;color: white;" type="button" class="btn btn-submit" onClick='submitDescriptionForm()'>Submit</button>
<button type="button" class="btn btn-submit" data-dismiss="modal">Cancel</button>
<!-- <input type='button' value='Save Project' class="btn-u btn-u-primary" onClick='submitDetailsForm2()' /> -->
</form>
</div>
<!-- ##################END MODAL CONTENT################ -->
<!-- </div> -->
</div>
</div>
</div>
</div>
</div>
<!-- ################End Bootstrap Modals With Forms #########################-->
i have faced the similar issue, in modal popup it also show scroll bar (css issues)while showing tooltip to solve that.. try to use default browser tooltip (title attribute),
modify your summernote.js file and add title attribute
My Summernote.js file - version 0.5.1
for example:
bold: function (lang) {
return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + lang.font.bold + '" data-shortcut="Ctrl+B" data-mac-shortcut="⌘+B" data-event="bold" tabindex="-1"><i class="fa fa-bold icon-bold"></i></button>';
},
italic: function (lang) {
return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + lang.font.italic + '" data-shortcut="Ctrl+I" data-mac-shortcut="⌘+I" data-event="italic" tabindex="-1"><i class="fa fa-italic icon-italic"></i></button>';
},
underline: function (lang) {
return '<button type="button" class="btn btn-default btn-sm btn-small" title="' + lang.font.underline + '" data-shortcut="Ctrl+U" data-mac-shortcut="⌘+U" data-event="underline" tabindex="-1"><i class="fa fa-underline icon-underline"></i></button>';
},
Hope this will help you
I will be completely honest. I found this code on internet explaining this would help out with tooltips. Completely forgot to save the site where I found this but it works like a charm.
$(document).on("show.bs.modal", '.modal', function (event) {
// console.log("Global show.bs.modal fire");
var zIndex = 100000 + (10 * $(".modal:visible").length);
$(this).css("z-index", zIndex);
setTimeout(function () {
$(".modal-backdrop").not(".modal-stack").first().css("z-index", zIndex - 1).addClass("modal-stack");
}, 0);
}).on("hidden.bs.modal", '.modal', function (event) {
// console.log("Global hidden.bs.modal fire");
$(".modal:visible").length && $("body").addClass("modal-open");
});
$(document).on('inserted.bs.tooltip', function (event) {
// console.log("Global show.bs.tooltip fire");
var zIndex = 100000 + (10 * $(".modal:visible").length);
var tooltipId = $(event.target).attr("aria-describedby");
$("#" + tooltipId).css("z-index", zIndex);
});
$(document).on('inserted.bs.popover', function (event) {
// console.log("Global inserted.bs.popover fire");
var zIndex = 100000 + (10 * $(".modal:visible").length);
var popoverId = $(event.target).attr("aria-describedby");
$("#" + popoverId).css("z-index", zIndex);
});
I hope this is useful for you as well.

Categories