reload page asynchronously after success ajax - javascript

i'm trying to add a new entered value to a table after success method runs using ajax , i've used ModelForm . i want to add the new entry to the table body row ! , i've tried alot , but still i cant figure it out ! i most appreciate your helps
class MainGroup(models.Model):
admin = models.ForeignKey(User,on_delete=models.CASCADE)
main_type = models.CharField(max_length=40,unique=True)
date = models.DateTimeField(auto_now_add=True)
my views.py
#login_required
def create_maingroup(request):
lists = MainGroup.objects.all().order_by('-pk')
form = MainGroupForm()
if request.is_ajax() and request.method == 'POST':
form = MainGroupForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.admin = request.user
obj.save()
return JsonResponse({'success':'success'})
else:
return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'})
context = {
'form':form,'lists':lists
}
return render(request,'products/create_maingroup.html',context)
const form = document.getElementById('main_form')
form.addEventListener("submit",submitHandler);
function submitHandler(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url 'products:create-maingroup' %}',
data : $('#main_form').serialize(),
dataType: 'json',
success: successFunction,
});
}
function successFunction(data) {
console.log(data.success=='success')
if (data.success=='success') {
form.reset();
obj = $('#main_form').serialize();
//i have to append new entred values here
//but i dont know how to get inputs and set the admin
//name who created the post !
alertify.success("added")
}
else if(data.error_code=='invalid'){
for(var key in data.error_msg){
if(key == 'main_type'){
document.getElementById('main_error').removeAttribute('hidden')
document.getElementById('main_error').innerHTML = data.error_msg[key][0]
}
}
}
}
my html page
<div class="col-md-12">
<div class="card card-info">
<div class="card-header">
<div class="card-tools">
<button type="button" class="btn btn-tool" data-toggle="collapse" data-target="#main_form" aria-expanded="false" aria-controls="main_form">
<i class="fas fa-minus"></i>
</button>
</div>
<h3 class="text-center">add new data</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form id="main_form" role="form" method="POST">{% csrf_token %}
<div class="card-body">
<div class="form-group row">
<label for="mainGroup" class="col-sm-2 control-label">name</label>
<div class="col-sm-10">
{{form.main_type | attr:'id:mainGroup'}}
<p id="main_error" class="alert alert-danger" aria-disabled="true" hidden></p>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success">add</button>
</div>
</form>
</div>
</div>
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="text-center">list of names</h3>
</div>
<div class="card-body table-responsive">
<table id="maingroupid" class="table table-bordered table-striped text-center">
<thead>
<tr>
<th>#</th>
<th>admin</th>
<th>name</th>
<th>date</th>
<th>actions</th>
</tr>
</thead>
<tbody id="tableData">
{% for i in lists %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{i.admin}}</td>
<td>{{i.main_type}}</td>
<td>{{i.date | date:'d-m-Y h:i A'}}</td>
<td align="center">
<button class="btn btn-info bg-info" onclick="editMain({{i.id}})" data-toggle="modal" data-target="#myModal"><i class="far fa-edit"></i></button>
<button class="btn btn-danger bg-danger" onclick="deleteMain({{i.id}})"><i class="far fa-trash"></i></button>
</td>
</tr>
{% endfor %}
</tbody>
</tfoot>
</table>
</div>
</div>
</div>
is it possible without refreshing the page and display the new data please ? i need it so much

You could return the new table once edited
context = {} # whatever your context is
return render(request, 'path/to/table/template.html', context=context)
template.html is the table element of your template
<thead>
<tr>
<th>#</th>
<th>admin</th>
<th>name</th>
<th>date</th>
<th>actions</th>
</tr>
</thead>
<tbody id="tableData">
{% for i in lists %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{i.admin}}</td>
<td>{{i.main_type}}</td>
<td>{{i.date | date:'d-m-Y h:i A'}}</td>
<td align="center">
<button class="btn btn-info bg-info" onclick="editMain({{i.id}})" data-toggle="modal" data-target="#myModal"><i class="far fa-edit"></i></button>
<button class="btn btn-danger bg-danger" onclick="deleteMain({{i.id}})"><i class="far fa-trash"></i></button>
</td>
</tr>
{% endfor %}
</tbody>
</tfoot>
Then on success within ajax use
success: function (data, status) {
$('#maingroupid`).html(data);
}

Related

Editable table dropdown issue

First of all I am very Junior about frontend developer and using the stackoverflow. I am editing a table with dropdown. But if I click all of the edit buttons it returns me last select in all dropdowns. It is a table that I want to edit.
And this is while I select all of the edit buttons.
function editBtn(event) {
var editTr = event.currentTarget.parentElement.parentElement.parentElement;
var al = $(editTr).find(".companyValue0")
var valName = $(editTr).find(".companyValue1")
var valMail = $(editTr).find(".companyValue2")
valSelect = al.text()
value01 = valName.text();
value02 = valMail.text();
//For remove and add active class
//
var select = `<select class="form-control" id="selectOption">
</select>`
var inputName = `<input class="form-control" value="${value01}" />`
var inputMail = `<input class="form-control" value="${value02}" />`
valName.html(inputName)
valMail.html(inputMail)
console.log("select",select)
al.html(select);
//
var departmentSelect = document.querySelectorAll("#selectOption")
console.log("depart", departmentSelect)
departmentSelect.forEach((item) => {
ajaxBrand(item,valSelect)
})
setButtonsEdit(event)
}
function ajaxBrand(opt,value) {
$.ajax({
type: "POST",
url: '{{ path('brand_selection') }}',
dataType: 'json',
data: {
name: name,
},
success: function (data) {
console.log("data", data)
var brandName = data.brands
for(let i = 0 ; i<= brandName.length-1 ; i++) {
opt.innerHTML += `
<option value="${brandName[i].id}">${brandName[i].name}</option> `
}
},
error: function (response) {
return false;
}
})
}
I hope you guys can help me.
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div class="card-body">
<div class=" dash-social table-content table-align">
<table id="table-list" class=" table table-striped table-bordered dt-responsive nowrap" style="border-collapse: collapse; border-spacing: 0; width: 100%;">
<thead class="thead-light">
<tr>
<th>Firma</th>
<th>Mağaza İsmi</th>
<th>E-posta</th>
<th></th>
</tr>
<!--end tr-->
</thead>
<tbody id="department-list">
{% for dealer in dealers %}
<tr data-id="{{ dealer.id }}" id="{{ dealer.brand.id }}">
<td class="companyValue0">{{ dealer.brand.name }}</td>
<td class="companyValue1">{{ dealer.name }}</td>
<td class="companyValue2">{{ dealer.mail }}</td>
<td name="buttons">
<div class="btn-group pull-right">
<button id="bEdit" type="button" class=" btn-sm btn-success shadow mr-1"
onclick="editBtn(event)"><i class="fas fa-edit"></i></button>
<button id="bElim" type="button" class=" btn-sm btn-danger shadow" onclick="deleteBtn(event)">
<i class="fas fa-trash"></i></button>
<button id="bAcep" type="button" class=" btn-sm btn-primary shadow mr-1" style="display:none;" onclick="acceptBtn(event)">
<i class="fas fa-check"></i></button>
<button id="bCanc" type="button" class=" btn-sm btn-info shadow" style="display:none;" onclick="cancelBtn(event)">
<i class="fas fa-times"></i></button>
</div>
</td>
</tr>
{% endfor %}
<!--end tr-->
</tbody>
</table>
<button class="btn btn-primary shadow" id="add" data-toggle="modal" data-target="#companyModal"><i class="fas fa-plus-circle"></i> Yeni Satır Ekle</button>
</div>
</div>
<!--end card-body-->
</div>
<!--end card-->
</div>
<!--end col-->
</div>
<!--end row-->

MVC4 Razor Modal not showing value passed into custom Javascript function with the onclick event handler

The modal opens. The "Id" value is displayed in the readonly textbox with id = "Id". But the Description value does not display in the readonly textbox with the id = "Description". I stepped through the code and the correct value is present in the function on the master view. However, it is not displaying in the modal. Am I missing something? Why is the value not passing to the Description id in the partial?
Partial
#model AutoClickItOnline.Models.AdminViewModels.DeleteSubTypeViewModel
#{
Layout = null;
}
#using (Html.BeginForm("DeleteSubType", "Admin", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, null, new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-12">
<label for="Id" class="text-dark">Subscription Type ID</label>
#Html.TextBoxFor(m => m.SubTypeId, new { #class = "form-control", #readonly = true, id = "Id" })
<label for="Name" class="text-dark pt-2">Descripiton</label>
#Html.TextBoxFor(m => m.Description, new { #class = "form-control", #readonly = true, id = "Description" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-success">Delete Subscription Type</button>
</div>
</div>
}
Javascript:
#section Scripts{
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#user_table').DataTable({
"scrollY": "50vh",
"scrollX": true,
"autowidth": false
});
});
function DeleteSubType(id, Description) {
$('#Id').val(id);
$('#Description').val(Description);
$('#DeleteSubTypeModal').modal('show')
}
</script>
}
Main View:
#model AutoClickItOnline.Models.AdminViewModels.SubscriptionTypeTableViewModel
#{
ViewBag.Title = "SubTypes";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<section>
<div class="container">
<div class="row py-5">
<div class="col">
<div class="modal fade" id="newSubTypeModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">New Subscription Type Entry</h2>
</div>
<div class="modal-body">
#{
Html.RenderPartial("/Views/Admin/AddSubTypePartial.cshtml", new SubscriptionType());
}
</div>
</div>
</div>
</div>
<div class="modal fade" id="DeleteSubTypeModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Delete Subscription</h2>
</div>
<div class="modal-body">
#{
Html.RenderPartial("/Views/Admin/DeleteSubTypePartial.cshtml", new AutoClickItOnline.Models.AdminViewModels.DeleteSubTypeViewModel());
}
</div>
</div>
</div>
</div>
<div class="d-flex flex-row">
<h2 class="pr-2">Subscription Type Manager</h2>
<a class="btn btn-sm btn-primary ml-auto my-2 text-light text-center d-none d-md-block" href="#" data-toggle="modal" data-target="#newSubTypeModal"><i class="fa fa-plus text-light pr-1"></i>Add New Subscription Type</a>
<a class="btn btn-sm btn-primary ml-auto my-2 text-light text-center d-sm-none" style="max-height:50px;" href="#" data-toggle="modal" data-target="#newSubTypeModal">ADD NEW</a>
</div>
#if (Model.Message != null)
{
<div class="text-danger">
#Html.DisplayFor(modelItem => Model.Message, null, new { #class = "text-danger" })
</div>
}
<hr />
<table id="user_table" class="display small-table table-bordered border-dark" style="width:100%;">
<thead>
<tr>
<th style="font-size:11px; min-width:195px;">Id</th>
<th style="font-size:11px;">Description</th>
<th style="font-size:11px;">Length</th>
<th style="font-size:11px;">Cost</th>
<th style="font-size:11px;">Active</th>
<th style="font-size:11px; min-width:100px;">Date/Time Created</th>
<th style="font-size:11px; min-width:60px;">Created By</th>
<th style="font-size:11px; min-width:105px;">Date/Time Modified</th>
<th style="font-size:11px; min-width:65px;">Modified By</th>
<th style="font-size:11px;">Delete</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.SubscriptionTypes)
{
<tr>
<td style="font-size:11px">#Html.DisplayFor(modelItem => item.SubscriptionTypeId)</td>
<td style="font-size:11px">#Html.DisplayFor(modelItem => item.Description)</td>
<td style="font-size:11px">#Html.DisplayFor(modelItem => item.Length)</td>
<td style="font-size:11px">$#Html.DisplayFor(modelItem => item.Cost)</td>
#if (item.Active)
{
<td style="font-size:11px">Yes</td>
}
#if (!item.Active)
{
<td style="font-size:11px">No</td>
}
<td style="font-size:11px">#Html.DisplayFor(modelItem => item.DateTimeCreated) UTC</td>
<td style="font-size:11px">#AdminHelpers.GetUsersName(item.CreatedBy)</td>
<td style="font-size:11px">#Html.DisplayFor(modelItem => item.DateTimeModified) UTC</td>
<td style="font-size:11px">#AdminHelpers.GetUsersName(item.ModifiedBy)</td>
<td>
<input type="button" class="btn btn-sm btn-danger" value="X" onclick="DeleteSubType('#item.SubscriptionTypeId', '#item.Description'); return false;" />
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</section>

Why my edit page didn't work in Laravel? I used vue.js

Basically, I'm doing a dashboard to view the details. If the user want to edit the their details. They should click the edit button to edit it.If i click the edit button it's didn't response anything. Now the edit didn't work. I couldn't find the problem. I attach my codes over here.
index.blade.php
#extends('layouts.main')
#section('content')
<div class="justpaddingside" role="main" >
<div class="row w-100 Bfont">
<div class="col-xs-12">
<div class="havence-content">
<div class="havence-content-body">
<div class="dashboardbg">
<div class="x_title" >
<img src="https://img.icons8.com/bubbles/50/000000/important-mail.png" class="rounded float-left" >
<h2 class="p-3 font-weight-bold">Email Reminder Dashboard</h2>
<h4 class="text-right">{{date('d-m-Y')}}</h4>
<h5 class="text-right">{{date('H:i:s')}}</h5>
</div>
<div class="col-md-12 text-right">
<a href="mail" class="btn btn-danger badge-pill" > Create New Template </a>
</div>
</div>
<div class="contentbg p-5">
<div class="row w-100">
<div class="havence-content-datatable table-responsive">
<table class="table table-hover table-info" cellpadding="0" cellspacing="0" border="0">
<thead class="">
<tr>
<th scope="col">ID</th>
<th scope="col">Subject</th>
<th scope="col">Message</th>
<th scope="col">Condition</th>
<th scope="col">Module Name</th>
</tr>
</thead>
<tbody>
#foreach ($mailTemplates as $mailTemplate)
<tr>
<th>{{$mailTemplate->id}}</th>
<th>{{$mailTemplate->subject}} </th>
<th>{{$mailTemplate->message}} </th>
<th>{{$mailTemplate->condition_id}} </th>
<th>{{$mailTemplate->mod_name}}</th>
<td class="text-right">
<a href='edit/{id}' class="btn btn-danger badge-pill" style="width:80px" >EDIT </a>
<form action="{{ route('havence.automail.delete', $mailTemplate) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{!! Form::open(['method'=>'post', 'id'=> 'delete-frm']) !!}
#method('DELETE')
#csrf
{!! Form::close() !!}
</div>
#endsection
#push('stylesheets')
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css">
#endpush
#push('scripts')
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>
<script src="https://unpkg.com/sweetalert2#7.19.3/dist/sweetalert2.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
#endpush
#section('page-js')
<script>
</script>
#endsection
AutoMailController.php
public function edit($id)
{
$mailTemplates=AutoEmailTemplate::find($id);
return view('havence.automail.edit')->with('mailTemplates', $mailTemplates);
}
web.php
Route::get('api/email/create', ['as' => 'email.create', 'uses' => 'Havence\AutoMailController#create']);
Route::get('automail/mail', 'Havence\AutoMailController#mail');
Route::get('automail/index',['as'=>'email.index','uses' => 'Havence\AutoMailController#index']);
Route::get('automail/edit/{id}',['as'=>'email.edit','uses' => 'Havence\AutoMailController#edit']);
Route::get('automail/delete',['as'=>'email.delete','uses' => 'Havence\AutoMailController#destroy']);
Try to use :
<a href='{{ route("email.edit",["id"=>$mailTemplate->id]) }}' class="btn btn-danger badge-pill" style="width:80px" >EDIT </a>
You're not passing the id from your href and user laravel string interpolation '{{ $variable }}'.
<a href='edit/{{$mailTemplate->id}}' class="btn btn-danger badge-pill" style="width:80px" >EDIT </a>
also if you want to open the route in another tab add target="_blank" in your 'a' tag.
<a href='edit/{{$mailTemplate->id}}' target='_blank' class="btn btn-danger badge-pill" style="width:80px" >EDIT </a>
what about replacing :
<a href='edit/{id}' class="btn btn-danger badge-pill" style="width:80px" >EDIT </a>
with:
<a href={{'edit/'.$mailTemplate->id}} class="btn btn-danger badge-pill" style="width:80px" >EDIT </a>

How to create a running total input field in django form?

How to create a running total using javascript in django form.
This is my model:
class Contra(models.Model):
date = models.DateField(default=datetime.date.today)
account = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='contraledgers')
class Particularscontra(models.Model):
contra = models.ForeignKey(Contra,on_delete=models.CASCADE,related_name='contras')
particular = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='particularcontra')
amount = models.DecimalField(max_digits=10,decimal_places=2,null=True)
This is my form:
class ContraForm(forms.ModelForm):
class Meta:
model = Contra
fields = ('date','account')
widgets = {
'date': DateInput(),
}
def __init__(self, *args, **kwargs):
super(ContraForm, self).__init__(*args, **kwargs)
self.fields['account'].widget.attrs = {'class': 'form-control select2',}
class ParticularscontraForm(forms.ModelForm):
class Meta:
model = Particularscontra
fields = ('particular','amount')
def __init__(self, *args, **kwargs):
super(ParticularscontraForm, self).__init__(*args, **kwargs)
self.fields['particular'].widget.attrs = {'class': 'form-control select2',}
self.fields['amount'].widget.attrs = {'class': 'form-control',}
Contra_formSet = inlineformset_factory(Contra, Particularscontra,
form=ParticularscontraForm, extra=6)
This
I tried this previously but was unsuccessful:
{% block content %}
<div class="content-wrapper">
<!-- <div class="container"> -->
<section class="content-header">
<!-- <div class="col-md-12 col-md-offset-4"> -->
<h1>
<strong>Company : {{company_details.Name}}</strong>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<!-- <li>Company list</li> -->
<li class="">Company list</li>
<li class="active">Create Simple Unit</li>
</ol>
<!-- </div> -->
</section>
<section class="content">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<!-- Horizontal Form -->
<div class="box">
<div class="box-header with-border">
{% if not form.instance.pk %}
<h3 class="box-title"><strong>Create Contra</strong></h3>
{% else %}
<h3 class="box-title"><strong>Update Contra</strong></h3>
{% endif %}
</div>
<!-- /.box-header -->
<!-- form start -->
<form method="POST" class="form-horizontal">
{% csrf_token %}
<div class="row">
<div class="col-md-12">
<div class="box box-success">
<div class="box-body form-responsive no-padding">
<br>
<br>
<div class="col-md-2">
<div class="form-group">
<label for="PAN1" class="col-md-4 control-label">Account<i class="material-icons" style="font-size:16px;color:red">*</i></label>
<div class="col-md-8">
{{ form.account }}
</div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="State1" class="col-md-4 control-label">Date<i class="material-icons" style="font-size:16px;color:red">*</i></label>
<div class="col-md-8">
{{form.date}}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="box box-success">
<div class="box-body table-responsive no-padding">
<table class="table">
{{ contras.management_form }}
<thead>
<tr>
<th class="col-md-6">Particulars<i class="material-icons" style="font-size:16px;color:red">*</i></th>
<th class="col-md-6">Amount<i class="material-icons" style="font-size:16px;color:red">*</i></th>
</tr>
</thead>
<tbody id="calculate">
{% for form in contras.forms %}
<tr class='{% cycle "row1" "row2" %} formset_row'>
<td class="col-md-6">{{ form.id }} {{ form.particular}}</td>
<td class="col-md-6 amounts">{{ form.amount}}</td>
</tr>
{% endfor %}
</tbody>
<tr>
<td class="col-md-6"></td>
<td class="col-md-6" id="totaled"><input type="text" name="total"></td>
</tr>
</table>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default" type="reset" value="Reset">Reset</button>
{% if not form.instance.pk %}
<button type="submit" class="btn btn-info pull-right" value="Submit">Create</button>
{% else %}
<button type="submit" class="btn btn-info pull-right" value="Submit">Update</button>
{% endif %}
</div>
<!-- /.box-footer -->
</form>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'add contra',
deleteText: 'remove',
prefix: 'contras'
});
</script>
<script type="text/javascript">
$(document).ready(function() {
let tableInstance = $('#calculate td.amounts');
let totals = 0;
tableInstance.each(function() {
totals = totals + Math.floor($(this).text() * 100) / 100;
});
$(".totaled :input").val(totals);
});
</script>
</section>
</div>
{% endblock %}
This is the javascript code I tried:
<script type="text/javascript">
$(document).ready(function(e){
$('#calculate tbody').change(function(){
var totals = 0;
$(".amounts").each(function(){
totals = totals + parseInt($(this).val());
})
$(".totaled").val(totals);
});
});
</script>
I am using inline formset in my template I want to display the running total of all the amount given in my inline form..
How is that possible to do it in django?
any guess?
Thank you
Not sure if someone is still looking for an answer to this. This is the code I used. 'total' is the id of a span element, where the running total is shown.
$("input.numberinput").change(function(){
sum=0
$("input.numberinput").each(function(){
sum += parseInt($(this).val());
})
$('#total').text(sum);
})
Select each td class amounts, iterate and add over them.
$(document).ready(function() {
let tableInstance = $('#calculate td.amounts');
let totals = 0;
tableInstance.each(function() {
totals = totals + Math.floor($(this).text() * 100) / 100;
});
$(".totaled :input").val(totals);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<table class="table" id="calculate">
<thead>
<tr>
<th class="col-md-6">Particulars <i class="material-icons" style="font-size:16px;color:red">*</i></th>
<th class="col-md-6">Amount <i class="material-icons" style="font-size:16px;color:red">*</i></th>
</tr>
</thead>
<tbody>
<tr class="row1 formset_row">
<td class="col-md-6">1</td>
<td class="col-md-6 amounts">5.2</td>
</tr>
<tr class="row2 formset_row">
<td class="col-md-6">2</td>
<td class="col-md-6 amounts">5.5</td>
</tr>
<tr>
<td class="col-md-6"></td>
<td class="col-md-6 totaled"><input type="text" name="total"></td>
</tr>
</tbody>
</table>

Thymeleaf pass data from html id to thymeleaf variable

I've a problem with below code. I need to pass a variable from html id to thymeleaf variable.
<table class="responsive-table highlight bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr th:each="worker: ${workersList}">
<td th:text="${worker.id}"></td>
<td th:text="${worker.name}"></td>
<td th:text="${worker.surname}"></td>
<td th:text="${worker.email}"></td>
<td>
<a href="#deleteModal" class="btn tooltipped modal-trigger" th:attr="data-id=${worker.id}, data-name=${worker.name +' '+ worker.surname}"
data-position="top" data-delay="50" data-tooltip="Delete"><i class="material-icons">delete</i></a>
</td>
</tr>
<!-- Delete Modal -->
<div id="deleteModal" class="modal modal-fixed-footer">
<div class="modal-content">
<p id="modal-name"></p>
<p id="modal-id"></p>
</div>
<div class="modal-footer">
<a th:href="#{'/delete/'+${modal-id} }" class="modal-action modal-close waves-effect waves-red btn-flat">Yes</a>
</div>
</div>
</tbody>
</table>
<script th:inline="javascript">
$('#deleteModal').modal({
ready: function(modal, trigger) {
var button = $(trigger);
var id = button.data('id');
$('#modal-id').html(id);
}
});
</script>
It won't work. I've to pass it using js because this id's are changeable depends on worker I click. This works, but It can't pass an id to th:href Thanks for help!
They way you have it done, you need to use Javascript to update the ID, as your modal is outside the loop. I would do something like this:
<div class="modal-footer">
<a id="idModalLink" href="#" class="modal-action modal-close waves-effect waves-red btn-flat">Yes</a>
</div>
And in your javascript code:
$('#deleteModal').modal({
ready: function(modal, trigger) {
var button = $(trigger);
var id = button.data('id');
$('#modal-id').html(id);
$('#idModalLink').attr("href", "/delete/" + id);
}
});

Categories

Resources