Laravel re-show modal with same data when validation error - javascript

I have Table showing data from database inside each row there is a button
opening a modal with the current clicked row id like following:
<tbody>
#foreach($receivedShipments as $shipment)
<tr>
<th class="text-center" scope="row">
{{ $loop->iteration }}
</th>
<td class="font-w600 font-size-sm">
<button type="button" class="btn btn-sm btn-light js-tooltip-enabled push"
data-toggle="modal" data-target="#modal_handle_national_id" data-id="{{$shipment->id}}"
data-original-title="{{trans('validation.attributes.deliver_to_receiver_customer')}}">
{{trans('validation.attributes.deliver_to_receiver_customer')}}</button>
</td>
</tr>
#endforeach
</tbody>
the Modal modal_handle_national_id is :
<div class="modal fade" id="modal_handle_national_id" >
<div class="modal-content">
<form class="js-validation" id="handleForm" action="" method="POST">
#csrf
#if(count($errors)>0)
<div class="alert alert-danger ">
<ul>#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<input type="text" class=" col-xl-8" id="receiver_customer_nationalId"
name="receiver_customer_nationalId"
value="{{ old('receiver_customer_nationalId') }}">
<button type="submit">Submit</button>
</form>
</div>
</div>
i have script to hadle the action link of the form according to clicked button row id:
<script>
#if (count($errors) > 0)
$('#modal_handle_national_id').modal('show');
#endif
$('#modal_handle_national_id').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
$('#handleForm').attr("action", "");
var id = button.data('id');
var url = '{{ route("shipments.handle", ":id") }}';
url = url.replace(':id', id);
$('#handleForm').attr("action", url);
});
</script>
i need the modal to be re-showed with the same old clicked button id when there is a Laravel validation error
Any Help please?

You can use hidden.bs.modal event:
This event is fired when the modal has finished being hidden from the
user (will wait for CSS transitions to complete).
The snippet:
$('#modal_handle_national_id').on('hidden.bs.modal', function(e) {
$(this).find('form').trigger('reset');
})

Related

input checkbox add duplicate data in third cycle on checked

I write down a function which is bulk deletion on table. There is a table with checkbox on every rows, if some one select checkboxs then click on delete button its shows a confirmation modal, if it is close them modal then no action occurs.
In my case when I checked the boxes modal shows correct selected data, and if I then unchecked their is no problem, problem occurs when third time checked it populate previous unchecked data in modal. means checked -> unchecked -> checked.
let newTableData = "";
$('.btn-delete-employees-table-danger').hide();
let modalValue = null;
let selectedID = null;
let selectedRow = ""
let counter = 0;
console.log($('.btndelete'));
$(document).on('click', '.btndelete', function(e) {
$('.btn-delete-employees-table-danger').show();
if ($(this).prop("checked") == true || this.checked) {
counter = counter + 1;
var id = $(this).closest('tr').data('id');
selectedRow = $(`.roww[data-id=${id}]`);
selectedID = $(this).closest('tr').attr('id');
$(this).closest('tr').addClass('deleteselectedrow')
if($(this).closest('tr').addClass('deleteselectedrow')) {
$('.counter-of-selected-emp-modal').html(`${counter} employees will be deleted`)
newTableData += `
<div class="card mt-3" id="emp-${selectedID}">
<div class="d-flex justify-content-between modal-row">
<div>
<h4>${selectedRow[0].cells[1].innerText}</h4>
<p class="light-small-grey-text">ID</p>
</div>
<div>
<h4>${selectedRow[0].cells[2].innerText}</h4>
<p class="light-small-grey-text">Emp Name</p>
</div>
<div>
<h4>${selectedRow[0].cells[3].innerText}</h4>
<p class="light-small-grey-text">Emp DOB</p>
</div>
<div>
<h4>${selectedRow[0].cells[4].innerText}</h4>
<p class="light-small-grey-text">Emp CNIC</p>
</div>
</div>
</div>
`
console.log(newTableData);
}
$('.data-in-modal').html(newTableData);
} else {
counter = counter - 1;
$('.counter-of-selected-emp-modal').html(`${counter} employees will be deleted`)
selectedID = $(this).closest('tr').attr('id');
console.log($(selectedRow[0].cells[0].childNodes[1].checked))
console.log($("#emp-"+selectedID));
$(this).prop('checked', false);
$("#emp-"+selectedID).remove();
$("#emp-"+selectedID).empty();
$(this).prop("checked") == false;
$("#emp-"+selectedID).addClass('d-none')
console.log($('.data-in-modal'));
console.log(newTableData);
}
if(counter == 0 ) {
$('.btn-delete-employees-table-danger').hide();
$('.data-in-modal').html("");
newTableData = '';
}
});
function getandsetdate() {
var date = new Date().toISOString('yyyy-mm-dd').split('T')[0];
var element = document.getElementById('date')
element.value = date
return date
}
// show confirmation modal
$('.shown-modal').on('click', function (e) {
var policy_date_elem = $('input[name="emp_policy_end"]')
policy_date_elem.val(getandsetdate())
policy_date_elem.css('border', '1px #ced4da solid')
$('#showsDependentModal').modal('show');
})
$('#btnDelteYes').click(function () {
$('.deleteselectedrow').remove();
console.log($('.deleteselectedrow'))
console.log($('.deleteselectedrow').prevObject[0]);
$('.btn-delete-employees-table-danger').hide();
newTableData = ""
$('#showsDependentModal').modal('hide');
});
$('.no-btn').click(function () {
$('tr').removeClass('deleteselectedrow')
$('#showsDependentModal').modal('hide');
})
<table class="table table-bordered sortable empy-table" id="table">
<thead class="">
<tr>
<th>
Select
</th>
<!-- <th>check</th> -->
<th>Emp ID</th>
<th>Employee Name</th>
<th>DOB</th>
<th>CNIC</th>
<th class="noExport">Details</th>
</tr>
</thead>
<tbody id="search-table" class="employees_body">
<!-- {% for employee in employees %}
<tr id="{{ employee.id }}" data-id="{{ forloop.counter }}" class="roww">
 <td>
<input class="btndelete" type="checkbox" name="employee_id" value="{{ employee.id }}" />
</td>
<td>
{{employee.id}}
</td>
<td>
{{employee.first_name}} {{employee.last_name}}
</td>
<td>
{{employee.date_of_birth}}
</td>
<td>
{{employee.cnic}}
</td>
<td class="noExport">
<a class="text-dark" href="{% url 'smartbenefits:employee_profile' employee.id %}">
<button class="button-detail"><span class="fa fa-info-circle"></span></button>
</a>
</td>
</tr>
{% endfor %} -->
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="modal hide fade" id="showsDependentModal" tabindex="-1" aria-labelledby="showssDependentModal" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content modal-secondary">
<div class="px-4 pt-5 w-100">
<div class="d-flex justify-content-between w-100">
<div class="">
<h4>Please confirm if you want to delete the below employees?</h4>
<p class="counter-of-selected-emp-modal"></p>
</div>
<i class="fa fa-window-close dependent-close-icons-modal no-btn" id="modal-dismiss" data-bs-dismiss="modal" aria-label="Close"></i>
</div>
</div>
<div class="modal-body">
<div class="data-in-modal ">
</div>
<div class="policy-end w-25 mt-3">
<!-- <input type="text" name="emp_policy_end" readonly vaule="" /> -->
<label class="date-detail" for="emp_policy_end">Policy End Date. <span
class="fa fa-info-circle"></span></label>
<span class="hover-message">Policy End date will be same as the current date. For further queries,
contact our ops team</span>
<input id="date" type="date" name="emp_policy_end" readonly />
</div>
</div>
<div class="modal-footer">
<button class="button-secondary active" id="btnDelteYes">Confirm</button>
</div>
</div>
</div>
</div>

What's the correct way to submit a single element in a list when each of them has a separate submit button

I have an event page which contains a list of participants. From there users can be invited to that event by opening a modal view containing a user list. Users are shown in the same modal with each having an 'Invite'(submit) button next to them. How can I let the controller action know which user is invited?
From what I could find, creating a form for each list element is bad and in addition displays warnings, but if I create a form element on top of the 'foreach', I then need to somehow find which user to submit.
Also thought about appending incrementing numbers to each of submit button name, but I still need to somehow map them to 'their' users.
Along with the invited user id, controller post action also needs to receive the event id.
Here's the code:
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Select user</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form id="eventMemberForm" method="post" class="col-sm-6 custom-close" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed" data-ajax-url="#Url.Action("SendInvitation", "Sports")">
<input type="hidden" asp-for="Invitation.FkEvent" value="#Model.Event.EventId" />
<input type="hidden" asp-for="Invitation.EventInvitationId" />
<div class="modal-body">
<input class="form-control p-2 mb-2" id="myInput" type="text" placeholder="Search..">
<h4 class="align-content-center">Users</h4>
<div class="form-group">
<table class="w-100">
<tbody id="myField">
#foreach (var item in Model.Users)
{
<tr>
<td class="d-flex">
<div> #Html.DisplayFor(modelItem => item.Text) </div>
<input type="hidden" asp-for="Invitation.FkUser" value="#item.Value" />
<div class="ml-auto">
<input id="btnSave" type="submit" value="Invite" class="btn btn-success" />
</div>
</td>
</tr>
++i;
}
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#myInput").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myField tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
completed = () => {
alert("User invited");
};
</script>
You can use jquery ajax to pass the parameters you need, through the click event, get the corresponding value of the control needed next to the current button.
By adding the name attribute to the submit button, and then triggered in jquery.
And add the id to the div that stores the Text value of User to facilitate finding the corresponding value in jquery.
#section Scripts{
<script>
$(document).ready(function () {
$("#myInput").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myField tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
$("[name=submitBtn]").click(function () {
event.preventDefault();
var obj = {
myUser: {
Text: $($(this).parent().siblings()[0]).text(),
Value: $($(this).parent().siblings()[1]).val()
},
eventId: $("#Invitation_FkEvent").val()
};
$.ajax({
url: $("#eventMemberForm").attr("data-ajax-url"),
method: 'post',
data: obj,
})
});
});
completed = () => {
alert("User invited");
};
</script>
}
<h1>Index</h1>
<button data-toggle="modal" data-target="#myModal" class="btn btn-primary">Submit</button>
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Select user</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form id="eventMemberForm" method="post" class="col-sm-6 custom-close" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed" data-ajax-url="#Url.Action("SendInvitation", "Sports")">
<input type="hidden" asp-for="Invitation.FkEvent" value="#Model.Event.EventId" />
<input type="hidden" asp-for="Invitation.EventInvitationId" />
<div class="modal-body">
<input class="form-control p-2 mb-2" id="myInput" type="text" placeholder="Search..">
<h4 class="align-content-center">Users</h4>
<div class="form-group">
<table class="w-100">
<tbody id="myField">
#foreach (var item in Model.Users)
{
<tr>
<td class="d-flex">
<div id="textValue"> #Html.DisplayFor(modelItem => item.Text) </div>
<input type="hidden" asp-for="Invitation.FkUser" value="#item.Value" />
<div class="ml-auto">
<input id="btnSave" type="submit" value="Invite" class="btn btn-success" name="submitBtn"/>
</div>
</td>
</tr>
++i;
}
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
</div>
Controller:
public IActionResult SendInvitation(User myUser, string eventId)
{
//do what you want
return View();
}

Django Login Form Submit Refreshing Page

I want to display an error in a bootstrap modal when a user submits an incorrect login form. Right now, the submitting the form just reloads the current page so I can't get the JSON response.
basic.html where the login modal appears
...
<button type="button" class="btn btn-secondary btn-sm" data-toggle="modal" data-target="#loginModal" id="login_modal_trigger">Log In</button>
{% include 'registration/login.html' with form=form %}
...
registration/login.html
<div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Log In</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="content-container" class="container p-none">
<div class="lgn-container col-lg-8">
<form id="login-form" method="post"
action="">
{% csrf_token %}
<table class="table">
<tr>
<td><label for="id_username">Username</label></td>
<td><input id="id_username" name="username"
type="text" class="form-control"></td>
</tr>
<tr>
<td><label for="id_password">Password</label></td>
<td><input id="id_password" name="password"
type="password" class="form-control"></td>
</tr>
</table>
{% if form.errors %}
<p class=" label label-danger">
Your username and password didn't match.
Please try again.
</p>
{% endif %}
<input type="submit" id="ajax_form_submit" value="Login"
class="btn btn-primary pull-right" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
script.js:
I figured event.preventDefault(); would prevent refreshing when there is an error.
$(document).ready(function() {
$("#login-form").submit(function(event) {
jQuery.ajax({
"data": $(this).serialize(),
"type": $(this).attr("method"),
"url": "{% url 'login_user' %}",
"success": function(response) {
// switch(response.code) {
// // Do what you want with the received response
// }
console.log(response);
if (response.code == 0) {
console.log("fail");
}
}
});
event.preventDefault();
});
});
project/urls.py
...
urlpatterns = [
...
url(r'^login/$', views.login_user, name='login_user'),
...
]
...
app/views.py
from django.contrib.auth import authenticate, login
def login_user(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
return HttpResponseRedirect(reverse('app:detail', args=(username,)))
else:
# Return an 'invalid login' error message.
response = {'code': 0}
return HttpResponse(response, content_type='application/json')
# return HttpResponse(status=404)
The login modal currently doesn't even work with my edits, but my main problem is the refreshing of the page after submitting instead of just giving me a response in JSON to then edit the HTML with. The js I use is mostly from other posts.
In your app/views.py you need to change else (that identify erro login) to:
return HttpResponseRedirect(reverse('app:login', args=(response,)))
Now you pass in the first parameter the name of your login view, and agr you send the 'response'.
In your template:
{% if code == 0 %}
<p class=" label label-danger">
Your username and password didn't match.
Please try again.
</p>
{% endif %}

PHP POST Array from window-modal

I have a web page that contain a table. Every rows has a checkbox. When the user select the rows, using checkbox, and push a button(I save the codes in array) It show a window-modal with four buttons(input). When click one of this buttons it launch a PHP page to update database.
Now when it showed the window modal I get an array with the codes of the selections rows and I do not know how to send this array(jquery code) to PHP page using POST method.
HTML code of window-modal:
<!-- CHANGE STATUS MODAL MENU -->
<div class="modal fade" id="change" tabindex="-1" role="dialog" aria-labelledby="change" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
<h4 class="modal-title custom_align" id="Heading">CANVIAR ESTAT</h3>
</div>
<form action="updateEstado.php" method="post">
<div class="modal-body">
<div class=" text-center">
<div class="container-fluid">
<div class="row">
<div class="col-md-12 text-center">
<input type="submit" class="btn btn-modal-estado" style="background-color:YellowGreen; color:white;" value="ACTIVAT">
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
<input type="submit" class="btn btn-modal-estado" style="background-color:Tomato; color:white;" value="PENDENT MIQUEL ALIMENTACIÓ">
</div>
</div>
<div class="row ">
<div class="col-md-12 text center">
<input type="submit" class="btn btn-modal-estado" style="background-color:SkyBlue; color:white;" value="PENDENT ADDCOM">
</div>
</div>
<div class="row">
<div class="col-md-12 text center">
<input type="submit" class="btn btn-modal-estado" style="background-color:Gray; color:white;" value="DESACTIVAT">
</div>
</div>
<div class="row">
<h5 id='codigosSeleccionados'></h5>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Jquery code:
/* CHANGE MODAL WINDOW */
$('#change').on('show.bs.modal', function (event) {
var arrayCod = new Array();
$('#tableprod').find('tbody tr').each(function () {
var $button = $(event.relatedTarget) // Button that triggered the modal
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
var field = $(this).data("field");
var cod;
$tds = row.find("td"); // get all table cells in that row
$.each($tds, function(index,value) {
var field = $(this).data("field");
if (field == 'codigo'){
cod = $(this).text();
console.log(cod);
arrayCod.push(cod);
return false;
}
});
}
if (arrayCod.length != 0){
$('input[type="submit"]').prop('disabled', false);
$('#codigosSeleccionados').text(arrayCod.length + " codis seleccionats");
} else {
$('input[type="submit"]').prop('disabled', true);
$('#codigosSeleccionados').text("Cap codi seleccionat");
}
});
//$('#codigosSeleccionados').text("CODIS SELECCIONATS: " + strCods);
console.log(arrayCod.length);
});
And PHP page:
$conn = dbConnect("localhost", "5432", "dbname", "dbuser", "dbpass");
$codigo = $_POST['codigo'];
$query = "UPDATE produccion.ma_producto SET estado={$estado} WHERE codigo={$codigo}";
$result = pg_query($conn, $query);
I'm not sure to how do it, Could I save in global php variable from jquery? Or Could I send the array with method post when it click on button? :(
Add all checked codes as a list of hidden fields with [], then PHP will receive them as a list as well. It should be on a form which one of those 4 buttons of the modal will submit:
var $form = $("form"); // The modal's form
arrayCod.forEach(function(cod) {
$('<input type="hidden" name="codigo[]" value="' + cod + '">').appendTo($form);
});
// Event handler for your modal's four buttons. They will submit the form
$('.modal').on('click', 'button', function() {
$form.submit();
});
Then in PHP:
$codigos = $_POST["codigos"]; // This will be an array
Example:
$("#open-modal").on("click", function() {
var checkedCodes = [];
// Get checked checkboxes
$("#codes input").each(function() {
if ($(this).is(":checked")) {
// Get the code from td's text
checkedCodes.push($(this).closest("tr").find("td:eq(1)").text());
}
});
// Add hidden fields to the "modal"'s form
var $modal = $("#modal-body"),
$form = $modal.find("form");
checkedCodes.forEach(function(code) {
$('<input type="hidden" name="codigos[]" value="' + code + '">').appendTo($form);
});
$modal.show();
});
$("#modal-body").on("click", "button", function() {
$("#modal-body").find("form").submit();
});
#modal-body {
display: none;
border: 1px solid #000
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="codes">
<tr>
<td><input type="checkbox"></td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>2</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>3</td>
</tr>
</table>
<button id="open-modal">Open Modal</button>
<div id="modal-body">
Imagine this is your modal
<form>
<button>Button #1</button>
<button>Button #2</button>
<button>Button #3</button>
<button>Button #4</button>
</form>
</div>
This code is just an example. I didn't even based it over your code.

on click event not working after first on click event.

I am a newbie to jquery. I have a page where I have two buttons. One of them is edit button, and the other one is delete button. When I click edit button it removes these two button and at the same place( the place where delete and edit button were before) I add three elements one of them is "save" button. This save button has a class - "save-btn". I select this button by jquery class selector. And onclick it should do something. But when I click nothing happens. Can anyone suggest whats wrong and give a solution. Thanks in advance.
<div class="container-fluid">
<div class="row">
<div class="col-md-2 "></div>
<div class="col-md-4 ">
<div class="form-tile">
<form action="" method="post">{% csrf_token %}
{% crispy form %}
</form>
</div>
</div>
<div class="col-md-4 tile">
<div class="row">
<div class="col-md-12">
<h2 style="margin-top: 0px;padding-top: 0px;text-align: center">Today's Purchase</h2>
</div>
</div>
<div class="row">
<table class="table table-hover">
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for item in items %}
<tr>
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td><button class="btn btn-primary edit-btn"><i class="fa fa-pencil-square-o"></i></button>
<button class="btn btn-danger delete-btn"><i class="fa fa-trash"></i></button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="col-md-2 "></div>
</div>
And here is my javascript
<script>
$(function(){
$(".edit-btn").click(function(){
var custom_form = '<td><input type="text" size="10"></td><td><input type="text" size="10"></td> <td><button class="btn btn-primary save-btn">Save</i></button> </td>'
var parent = $(this).parent().parent().html(custom_form);
});
$(".save-btn").click(function(){
alert("asnlas");
});
});
</script>
when you create an element you must assign the event at the same time
Try this....
$(function(){
$(".edit-btn").click(function(){
var custom_form = '<td><input type="text" size="10"></td><td><input type="text" size="10"></td> <td><button class="btn btn-primary save-btn">Save</i></button> </td>'
var parent = $(this).parent().parent().html(custom_form);
$(".save-btn").click(function(){
alert("asnlas");
});
});
});

Categories

Resources