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>
Related
I have this error
invalid literal for int() with base 10: '" + key + "'
I generate the
session['Exit'] is a dictionary inside a dictionary
DictItems = {index:{'foo':foo.foo, ...}}
where index is a int
generated like this
numkey = len(session['Exit'])
ind = int(numkey) + 1
index = str(ind)
The code I was trying to create is
<div class="container-fluid">
<div class="row">
<table class='table table-responsive table-sm w-auto small'>
<tbody>
<div class="col-xs-2">
{% for key, items in session['Exit'].items() %}
{% if key %}
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#new_value" data-key="{{key}}" data-price="{{items.price}}" onclick="updateModal(this)">
{{items.price}}
</button>
{% endif %}
{% endfor %}
</div>
</tbody>
</table>
</div>
</div>
<!--Modal -->
<div class="modal fade" id="new_value" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" 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">New_Value</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="modal-form" action="" method='POST' >
<div class="modal-body">
<p id="modal-text"></p>
<input class="form-control" name="new_value" step="any" required>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit">Change</button>
</form>
</div>
</div>
</div>
</div>
<!---Modal -->
{% if session['Exit'] %}
<script>
function updateModal(element) {
var key = element.dataset.key;
var price = element.dataset.price;
var form = document.getElementById("modal-form");
form.action = "{{url_for('salidas.change_price', key=" + key + ")}}";
document.getElementById("modal-text").innerHTML = "you are going to change the value $" + price + ", are you sure?";
document.getElementsByName("new_value")[0].value = price;
}
</script>
{% endif %}
I imagine that it coud be because the session['Exit'] could be empty, so i tried a {% if session['Exit'] %} but stop working when session has elements and gives the error
still if session session['Exit'] doesnt exist it shouldnt render
in other: i tried to make the key int
data-key="{{key|int}}
also in the script
var key = parseInt(element.dataset.key);
and in the key
+ parseInt(key) +
still in the url_for because is a string shouldnt give me a problem
so i tried to make the url like this in a triple level
form.action = "\"{{url_for('salidas.change_price', key=" + key + ")}}\"";
i still have the same problem
any idea what else could i try?
EDIT: the solution
basically as Detlef said
"doesn't know about the javascript variable key"
the reason escapes my understanding, because this string
document.getElementById("modal-text").innerHTML
works
so what i did is in the button that calls the data-key, renamed it to data-url and generated the url_for
and from there i just called it, leaving something like this
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#new_value" data-url="{{url_for('salidas.change_price', code=key)}}" data-price="{{items.price}}" onclick="updateModal(this)">
{{items.price}}
</button>
and the javascript
<script>
function updateModal(element) {
var url = element.dataset.url;
var price = element.dataset.price;
var form = document.getElementById("modal-form");
form.action = url;
document.getElementById("modal-text").innerHTML = "you are going to change the value $" + price + ", are you sure?";
document.getElementsByName("new_value")[0].value = price;
}
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.
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')
});
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.
In my strongly typed view I am looping over a list of objects coming from a database. Each of these objects is presented in a jumbotron, which has a button "Had role before". On click the modal opens and there I want to input some data in input boxes and save it to my database via an ajax call. One part of data that I want to input is the unique id which each object in the loop has. With the code I have so far I managed on click to get the id of the first object, but when I am clicking the buttons for the rest of the objects nothing happens.
This is the script in my view :
<script type="text/javascript">
$(document).ready(function () {
$(function () {
var idW;
$('#mdl').on('click', function () {
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="mdlname"]').val();
var id = parent.find('input[name="mdlwrid"]').val();
var idW = id;
console.log(idW);
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
$('#myModal').modal('show');
});
});
$('#mdlSave').on('click', function () {
console.log('x');
addPastRoleAjax();
});
function addPastRoleAjax() {
$.ajax({
type: "POST",
url: '#Url.Action("addPastRole", "WorkRoles")',
dataType: "json",
data: {
wrId: idW,
dateStart: $("#wrdateStart").val(),
dateEnd: $("#wrknamedateEnd").val()
},
success: successFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
</script>
the loop :
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="mdlwrid" value="#item.WorkRoleId" />
<input type="hidden" name="mdlname" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" id ="mdl" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
The modal :
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
<input id="wrdateStart" class='date-picker' />
<input id="wrknamedateEnd" class='date-picker' />
</div>
<div class="modal-footer">
<button type="button" id="mdlSave" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
Your problem is in the following piece of code:
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="mdlwrid" value="#item.WorkRoleId" />
<input type="hidden" name="mdlname" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" id ="mdl" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
You have used a foreach loop and inside it you create button elements with same id.
<button type="button" id ="mdl" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button>
So,foreach let you to create many buttons with same id. That's wrong and that's why you get that behavior(only first button work).The solution: Use classes instead.