update existing post called using dictionary , using ajax - django - javascript

i'm trying to go update page . my models.py
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 list_maingroup(request):
lists = MainGroup.objects.all().order_by('-pk')
data = []
for i in lists:
item = {
'id':i.id,
'admin':i.admin.username,
'main_type':i.main_type,
'date':i.date
}
data.append(item)
return JsonResponse({'data':data})
and this is my template
$.ajax({
type:'GET',
url:'/list-main-group',
success:function(data){
data = data.data
spinnerBox.classList.add('non-visible')
var k = '<tbody>'
for(i = 0;i < data.length; i++){
const date = new Date(data[i]["date"]).toLocaleString();
const id = parseInt(data[i]['id'])
// const url = '{% url "products:update_maingroup" %}'
// const my_url = url + "/"+id
k+= '<tr>';
k+= '<td>' + data[i]['id'] + '</td>';
k+= '<td>' + data[i]["admin"] + '</td>';
k+= '<td>' + data[i]["main_type"] + '</td>';
k+= '<td>' + date + '</td>';
k+= '<td align="center">'+
'<button class="btn btn-info bg-info" id="update" data-url='+{% url "products:update_maingroup" id %}+ '><i class="far fa-edit"></i></button>'+
' <button class="btn btn-danger btn-del bg-danger" data-did='+parseInt(data[i]["id"])+"><i class='far fa-trash'></i></button>"+
'</td>';
k+= '</tr>'
}
k+='</tbody>'
tableBody.innerHTML = k
$('#maingroupid').dataTable({
"order": [[ 0, "desc" ]]
});
},
// error:function(error){
// console.log(error)
// }
});
<div class="card-body table-responsive" >
<div id="spinner-box" class="spinner-border text-primary text-center" role="status">
</div>
<table id="maingroupid" class="table table-bordered table-striped text-center">
<thead>
<tr>
<th>#</th>
<th>{% trans "admin" %}</th>
<th>{% trans "name" %}</th>
<th>{% trans "date" %}</th>
<th>{% trans "options" %}</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</tfoot>
</table>
</div>
i've tried several ways to achieve that but still none of them worked , and this my views.py to update
#login_required
def update_maingroup(request,id):
obj = get_object_or_404(MainGroup,id=id)
form = MainGroupForm(instance=obj)
if request.is_ajax() and request.method == 'POST' and request.user.is_superuser:
if form.is_valid():
form = MainGroupForm(request.POST,instance=object)
form.save()
return JsonResponse({'success':'success'})
else:
return JsonResponse({'success':False,'error_msg':form.errors,'error_code':'invalid'})
context = {'form':form,'obj':obj}
return render(request,'update_maingroup.html',context)
and my update_maingroup.html
<form id="main-form" role="form" method="POST" action="{% url 'products:update_maingroup' id=obj.id %}">{% csrf_token %}
<div class="card-body">
<div class="form-group row">
<label for="mainGroup" class="col-sm-2 control-label">{% trans "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>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-success">{% trans "save" %}</button>
</div>
</form>
my urls.py to update
path('maingroup/update/<int:id>',update_maingroup,name='update_maingroup'),
path('list-main-group',list_maingroup,name='list-maingroup'),
but it raise this error :
Reverse for 'update_maingroup' with no arguments not found. 1 pattern(s) tried: ['maingroup/update/(?P[0-9]+)$']
is there something i have to change or add please ? thank you for helping ..

You are mixing Django template tags with JavaScript in your template:
{% url "products:update_maingroup" id %}
This does not work because the template tag only gets evaluate once when the template is rendered, not when the JavaScript get executed.
You have to generate the URL in your view:
#login_required
def list_maingroup(request):
lists = MainGroup.objects.all().order_by('-pk')
data = []
for i in lists:
item = {
'id':i.id,
'admin':i.admin.username,
'main_type':i.main_type,
'date':i.date,
'url': reverse("products:update_maingroup", kwargs={"id": i.id})
}
data.append(item)
return JsonResponse({'data':data})
In your template:
...
'<button class="btn btn-info bg-info" id="update" data-url='+data[i]["url"] + '><i class="far fa-edit"></i></button>'+
...
There are a bunch of alternatives:
you can create a "template URL" with a dummy values and replace those
var urlTemplate = "{% url "products:update_maingroup" 9999 %};
var url = urlTemplate.replace("9999", id);
you can use a third-party library that provides URL reversal in JavaScript, e.g. django-js-reverse

Related

My html data isn't displayed because of my javascript

So i started to build a basic website as a practice, and i got until i have a basic html, containing a table of informations, and a form, where you can add to the html through javascript.
My html looks like this
<body>
<hr>
<p class="display-4 text-center">Termék lista</p>
<table class="table">
<thead>
<tr>
<th scope="col">Termék Név</th>
<th scope="col">Termék Azonosító</th>
<th scope="col">Termék Ár</th>
<th scope="col">Termék leírás</th>
<th scope="col">Raktáron</th>
<th scope="col">Törlés</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>mangó</td>
<td>1</td>
<td>499 Ft</td>
<td>Gyümi</td>
<td>Van</td>
<td> <button class="delete btn btn-primary">X</button> </td>
</tr>
</tbody>
</table>
<div class="container mt-5">
<div class="bg-success p-5">
<form id="input-form">
<p class="display-4 text-center">Termékek hozzáadása</p>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputProduct">Termék</label>
<input type="text" class="form-control" id="inputProduct" name="productName">
</div>
<div class="form-group col-md-6">
<label for="inputCode">Termék Azonosító</label>
<input type="number" class="form-control" id="inputCode" name="productCode">
</div>
</div>
<div class="form-group">
<label for="inputPrice">Termék Ára</label>
<input type="number" class="form-control" id="inputPrice" name="productPrice">
</div>
<div class="form-row">
<div class="form-group col-md-8">
<label for="inputDesc">Termék Leírás</label>
<select id="inputDesc" name="inputDesc">
<option value="Gyümölcs">Gyümölcs</option>
<option value="Zöldség">Zöldség</option>
</select> </div>
<div class="form-group col-md-4">
<label for="inputSupply">Raktáron </label>
<select id="inputSupply" name="productSupply">
<option value="Van">Van</option>
<option value="Nincs">Nincs</option>
</select>
</div>
</div>
<button id="submit-button" type="submit" class="btn btn-primary">Hozzáadás</button>
</form>
</div>
</div>
And this is my javascript code so far:
var products = [
{
productName:"körte",
productCode: 2,
productPrice: 30,
productDesc: "Gyümi",
productSupply: "Nincs",
productId: 1
},
{
productName: "répa",
productCode: 3,
productPrice: 20,
productDesc: "Gyümi",
productSupply: "Van",
productId: 5
},
{
productName: "paradicsom",
productCode: 4,
productPrice: 50,
productDesc: "Gyümi",
productSupply: "Nincs",
productId: 6
}
]
var table = '<tbody>'
for( i = 0; i < products.length; i++){
table += `<tr>`;
table += `<td>` + products[i].productName + `</td>`;
table += `<td>` + products[i].productCode + `</td>`;
table += `<td>` + products[i].productPrice + `</td>`;
table += `<td>` + products[i].productDesc + `</td>`;
table += `<td>` + products[i].productSupply + `</td>`;
table += `<td> <button class="delete btn btn-primary" id="${products[i].productId}">X</button> </td>`
table += '</tbody>';
}
document.getElementById('tbody').innerHTML = table;
const tBody = document.getElementById("tbody")
tBody.addEventListener("click", function(x){
console.log("remove from tomb");
console.log(x.target);
console.log("gomb id: " + x.target.id);
for (let i = 0; i < products.length; i++) {
console.log("tomb i id: " + products[i].productId);
if (x.target.id == products[i].productId) {
console.log("removed");
products.splice(i, 1);
}
}
if(x.target.classList.contains("delete")) {
x.target.parentElement.parentElement.remove();
}
console.log(products);
})
const productInput = document.getElementById("inputProduct");
const codeInput = document.getElementById("inputCode");
const priceInput = document.getElementById("inputPrice");
const descInput = document.getElementById("inputDesc");
const supplyInput = document.getElementById("inputSupply");
const submitButton = document.getElementById("submit-button");
const addProduct = (ev) => {
ev.preventDefault();
let newProduct ={
productName: document.getElementById("inputProduct").value,
productCode: document.getElementById("inputCode").value,
productPrice: document.getElementById("inputPrice").value,
productDesc: document.getElementById("inputDesc").value,
productSupply: document.getElementById("inputSupply").value,
productId: Date.now()
}
let newRow = document.createElement("tr");
newRow.innerHTML += `
<td>${newProduct.productName}</td>
<td>${newProduct.productCode}</td>
<td>${newProduct.productPrice}</td>
<td>${newProduct.productDesc}</td>
<td>${newProduct.productSupply}</td>
<td> <button class="delete btn btn-primary" id="${newProduct.productId}">X</button> </td>`
tBody.appendChild(newRow);
products.push(newProduct);
document.querySelector('form').reset();
console.warn("added", {products});
}
document.addEventListener("DOMContentLoaded", ()=>{
submitButton.addEventListener("click", addProduct)
})
The problem is, as you can see i already have a product in the html, but i think my javascript for function, which displays the data from the .js overwrited the data from the html, thus displaying only the 3 products from javascript var = products. How can i have both the html data and the javascript data displayed simultaneously, so i have all 4 products when i open my .html?
Just modify this line as following. Hope to help, my friend :))
document.getElementById('tbody').innerHTML += table;
Here is the output:
http://jsfiddle.net/3zd0y64n/

How to find the closest table row using jQuery?

I have problem getting the value of the replace new table row, I will let you show the codes for the replacing new table row.
The is the Table B, Where this code use for replacing new table row to the Table A
$('#edit_chainingBuild').on('click','tr.clickable-row',function(e){
$('table#edit_chainingBuild tr').removeClass('selected');
$(this).addClass('selected');
var find_each_id_will_update = $(this).find('.data-attribute-chain-id').attr('data-attribute-chain-id');
$('.id_to_update_chain').val(find_each_id_will_update);
var find_each_id_condiments = $(this).find('.data-attribute-chain-id').attr('data-attribute-condiments-section-id');
$.ajax({
url:'/get_each_id_section_condiments',
type:'get',
data:{find_each_id_condiments:find_each_id_condiments},
success:function(response){
var get_each_section = response[0].condiments_table;
$.each(get_each_section, function (index, el) {
var stringify = jQuery.parseJSON(JSON.stringify(el));
var cat_condi_screen_name = stringify['cat_condi_screen_name'];
var cat_condi_price = stringify['cat_condi_price'];
var cat_condi_image = stringify['cat_condi_image'];
var condiment_section_name = stringify['condiment_section_name'];
var image = '<img src=/storage/' + cat_condi_image + ' class="responsive-img" style="width:100px;">';
// $('#edit_chainingBuild').append("<tr class='clickable-row'><td>" + Qty + "</td><td class='clickable-row-condiments'>" + Condiments + "</td><td>" + Price + "</td><td style='display:none;' data-attribute-chain-id="+menu_builder_details_id +" class='data-attribute-chain-id'>"+menu_builder_details_id+"</td></tr>");
$('table#edit_table_chaining_condiments').append("<tr class='edit_condimentsClicked' style='font-size:14px; border:none;'><td>"+condiment_section_name +"</td><td class='edit_condimentsScreenNameClicked'>" + cat_condi_screen_name + "</td><td class='edit_condimentsScreenPriced'>" + cat_condi_price + "</td><td>"+image+"</td></tr>");
});
$("table#edit_table_chaining_condiments tr").click(function(e){
var tableBhtml = $(this).closest('tr').html();
var condiments_name = $(this).closest("tr").find(".edit_condimentsScreenNameClicked").text();
var condimentsScreenPriced = $(this).closest("tr").find(".edit_condimentsScreenPriced").text();
// var input = '<input type="number" id="qty" name="qty" class="form-control changeQuantity" value="1" min="1">';
var id_to_edit_build = $('.id_to_update_chain').val();
$("#edit_chainingBuild tr.selected").html('');
var id_to_edit_builders = $('.id_to_update_chain').val();
$("#edit_chainingBuild tr.selected").replaceWith("<tr data-attribute-chain-id=" + id_to_edit_build + " class='clickable-row'><td class='new_condiments_name'>"+condiments_name+"</td><td>"+condimentsScreenPriced+"</td><td style='display:none;' data-attribute-chain-id="+id_to_edit_builders +" class='data-attribute-chain-id'>"+id_to_edit_builders+"</td></tr>");
$('#EditcondimentsBuilderModal').modal('hide');
});
},
error:function(response){
console.log(response);
}
});
$('#EditcondimentsBuilderModal').modal('show');
});
Looking forward if the table row already replace, I want to get the value of the class of new_condiments_name. So I create a variable to find the class of new_condiments_name. It look like this.
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
So now when I try alert the variable new_condiments_name using the click function it shows null only.
$('.edit_build_success_insert').click(function(){
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
alert(new_condiments_name);
});
My Html Table:
<div class="modal-body">
<div class="container">
<div class="header" style="text-align: center;">
<br>
<h3 style="color:#007BFF;">Build Your Chain Button</h3>
<label>This button will be served as customers menu.</label><br>
<i class="fab fa-creative-commons-remix" style="font-size:70px;"></i>
<br><br>
<input type="hidden" value="" class="edit_hidden_noun_id" name="">
<table class="table table-hover" id="edit_chainingBuild">
<thead>
<tr style="font-size: 15px;">
<!-- <th scope="col">Qty</th> -->
<th scope="col">Condiments</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody style="font-size:14px;">
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="edit_build_success_insert btn btn-primary">Build Done</button>
</div>
I have here the image to proof that the value that i get always null.
$('table .edit_build_success_insert').click(function(){
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
alert(new_condiments_name);
});

How do I insert a new form table row with JavaScript and get it included in what's passed to the controller?

Context
ASP.NET Core 2.0 MVC / EF Core / C#
Issue
I've a View used to create a new parent row and associated child rows, the later in an html table. Initially one blank child row is displayed. This all gets submitted to a Create Controller action to handle the database add and it works fine. The coding looks like this:
#using DBWTools.ViewModels
#model IssueViewModel
#section css {
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
}
<h2>New Issue</h2>
<hr />
<form asp-controller="Home" asp-action="CreateIssue" method="post" id="CreateIssueForm">
<div asp-validation-summary="All" class="text-danger"></div>
#* Parent row coding goes here. Removed for brevity *#
<div class="row">
<div class="col-md-12">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th class="col-md-1">Date</th>
<th class="col-md-10">Comment</th>
<th class="col-md-1">
<button type="button" onclick="appendIssueComment()" class="btn btn-primary"
data-toggle="tooltip" title="Add another comment">
<span class="glyphicon glyphicon-plus" />
</button>
</th>
</tr>
</thead>
<tbody class="commentBody">
#for (int i = 0; i < Model.Comments.Count; i++)
{
<tr class="commentRow">
<td>
<input asp-for="#Model.Comments[i].DateCreated" class="form-control" type="date" asp-format="{0:yy-MM-dd}" />
</td>
<td>
<textarea asp-for="#Model.Comments[i].Narrative" class="form-control"></textarea>
</td>
<td style="display:none"><input asp-for="#Model.Comments[i].ID" type="hidden" /></td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="form-horizontal">
<div class="col-md-1">
<button type="submit" class="btn btn-primary">Create</button>
</div>
</div>
</div>
</form>
#section Scripts {
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
#await Html.PartialAsync("_ValidationScriptsPartial")
<script src="~/js/AppendIssueComment.js" type="text/javascript"></script>
}
The table includes a button with an onClick action which runs a JavaScript function to add an extra row to the table. The function is:
function appendIssueComment() {
$(".commentBody").append("<tr>" +
"<td><input class='form-control' type='date' data-val='true' data-val-required='The Date created field is required.' id='Comments_0__DateCreated' name='Comments[0].DateCreated' value=''/></td >" +
"<td><textarea class='form-control' data-val='true' data-val-required = 'The Narrative field is required.' id='Comments_0__Narrative' name='Comments[0].Narrative'></textarea></td >" +
"<td style = 'display:none'><input type='hidden' data-val='true' data-val-required='The ID field is required.' id='Comments_0__ID' name='Comments[0].ID' value='0'/></td > " +
"</tr >");
}
This adds the new blank row successfully and data can be keyed into it. However when the form is submitted the new row is not passed to the controller.
Question
How can I add new rows to my HTML table and have them successfully passed to the controller?
EDIT
Updated function as per the #tchelidze solution
function appendIssueComment() {
var lastRow = $("[id$='__ID']").length.toString();
$(".commentBody").append("<tr>" +
"<td><input class='form-control' type='date' data-val='true' data-val-required='The Date created field is required.' id='Comments_" + lastRow + "__DateCreated' name='Comments[" + lastRow + "].DateCreated' value=''/></td >" +
"<td><textarea class='form-control' data-val='true' data-val-required = 'The Narrative field is required.' id='Comments_" + lastRow + "__Narrative' name='Comments[" + lastRow + "].Narrative'></textarea></td >" +
"<td style = 'display:none'><input type='hidden' data-val='true' data-val-required='The ID field is required.' id='Comments_" + lastRow + "__ID' name='Comments[" + lastRow + "].ID' value='0'/></td > " +
"</tr >");
}
New row is always bound to Comments[0] element, you have to increment index for each row.

pass a twig variable as a parameter for a javascript function

I have a datatable that I need to add rows dynamically throught t.row.add(), the table is composed by 4 columns, one of them has buttons inside, those buttons are Show & Edit, and they need the {{ row.id }} so the can be shown or edit, the problem is that I don't know how get the twig variable works. Here is my table code:
<table class="table table-striped table-bordered table-hover" id="sample_2">
<thead>
<tr>
<th class="table-checkbox noprint" style="text-align:center;">
<input type="checkbox" class="group-checkable" data-set="#sample_2 .checkboxes" disabled/>
</th>
<th width="40%" style="text-align:center;">
Valoraciones
</th>
<th width="20%" style="text-align:center;">
Estado
</th>
<th width="20%" style="text-align:center;" class="noprint">
Acciones
</th>
</tr>
</thead>
<tbody>
{% for valoracion in valoracion %}
<tr class="odd gradeX" id="fila{{ valoracion.id }}">
<td class="noprint">
<input type="checkbox" class="checkboxes" disabled/>
</td>
<td style="text-align:center;" id="valoracion">
{{ valoracion.descripcion }}
</td>
{% if valoracion.enabled == 1 %}
<td style="text-align:center;" id="estadoValEnable">Activo</td>
{% else %}
<td style="text-align:center;" id="estadoValEnable">Inactivo</td>
{% endif %}
<td style="text-align:center;" class="noprint">
<a class="btn btn-sm default" data-toggle="modal" onclick="showMantenimientoValoracion({{valoracion.id}})">Ver</a>
<a class="btn btn-sm blue" data-toggle="modal" onclick="editMantenimientoValoracionDetails({{valoracion.id}})">Editar</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
and here is the action to create a new row (the create action is in a modal view):
function sendDataCreateValoracionDetails() {
if ($('#CrearValoracionMantenimiento').val() == "") {
Notificacion("error", "La descripión de la competencia no puede estar vacía");
$('#CrearValoracionMantenimiento').focus();
} else {
$.blockUI({
baseZ: 20000,
message: '<h4><img src="{{ asset('
assets / global / plugins / cubeportfolio / cubeportfolio / img / cbp - loading.gif ') }}" /> Guardando datos, por favor espere...</h4>'
});
var form = document.getElementById("formCreateMantenimientoValoracionDetails");
var formData = new FormData(form);
$.ajax({
url: '{{ path('
createValoracionMantenimiento ') }}',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(returndata) {
if (returndata.success == true) {
$.unblockUI();
$('#crearValoracion').modal('hide');
Notificacion("success", "Valoración RP", "Los datos se han guardado correctamente.");
if ($('#EstadoValoracion').attr('checked')) {
var status = "Activo";
} else {
var status = "Inactivo";
}
$(document).ready(function() {
var t = $('#sample_2').addClass('centro').DataTable();
$("#sample_2").each(function() {
t.row.add([
'<tr>' +
'<td><input type="checkbox" class="checkboxes" disabled/></td>',
'<td>' + ($("#CrearValoracionMantenimiento").val()) + '</td>',
'<td>' + status + '</td>',
'<td ><a class="btn btn-sm default" data-toggle="modal" onclick="showMantenimientoValoracion(' {
{
valoracion.id
}
}
')">Ver</a><a class="btn btn-sm blue" data-toggle="modal" onclick="editMantenimientoValoracionDetails(' {
{
valoracion.id
}
}
')">Editar</a></td></tr>',
]).draw(false);
});
});
} else {
if (returndata.success == false) {
$.unblockUI();
Notificacion("error", "Valoración RP", "Existe una valoración igual.");
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
Notificacion("error", "Valoración RP", "Ha existido un problema y no se ha podido crear la valoración.");
$.unblockUI();
}
});
}
}
These are my buttons:
<a class="btn btn-sm default" data-toggle="modal" onclick="showMantenimientoValoracion('{{ valoracion.id }}')">Ver</a>
<a class="btn btn-sm blue" data-toggle="modal" onclick="editMantenimientoValoracionDetails('{{ valoracion.id }} ')">Editar</a>
and these are the twig parameters I need to pas inside the functions:
onclick="showMantenimientoValoracion('{{ valoracion.id }}') ///
onclick="editMantenimientoValoracionDetails('{{ valoracion.id }} ')`
here is the function code:
if ($('#EstadoValoracion').attr('checked')) {
var status = "Activo";
} else {
var status = "Inactivo";
}
$(document).ready(function() {
var t = $('#sample_2').addClass('centro').DataTable();
$("#sample_2").each(function() {
t.row.add([
'<tr>' +
'<td><input type="checkbox" class="checkboxes" disabled/></td>',
'<td>' + ($("#CrearValoracionMantenimiento").val()) + '</td>',
'<td>' + status + '</td>',
'<td ><a class="btn btn-sm default" data-toggle="modal" onclick="showMantenimientoValoracion(' {
{
valoracion.id
}
}
')">Ver</a><a class="btn btn-sm blue" data-toggle="modal" onclick="editMantenimientoValoracionDetails(' {
{
valoracion.id
}
}
')">Editar</a></td></tr>',
]).draw(false);
});
});
Thanks everyone :)
A twig variable can be readed by using .twig extension to the file name ends , When I need to use a variable twig inside javascript function, I create it inside file twig. There is not another way.
Just remove the quotes from the twig variable -
onclick="showMantenimientoValoracion('{{ valoracion.id }}')
should be
onclick="showMantenimientoValoracion({{ valoracion.id }})
And in your javascript function add the parameter -
function sendDataCreateValoracionDetails(valoracion_id) {
console.log(valoracion_id)
// Your code goes here
}
This should do it.

JS: pass variable onclick

I'm trying to pass a variable to a function, I know there are many topics about this, and I've nearly tried all suggestions, but still can't get it to work, these are my attempts:
edit: without the onclick, everything is working fine
var filename = file.name;
<button class="btn btn-danger delete" onclick="deleteImage(\''+filename+'\');">
results in: Uncaught SyntaxError: Unexpected token ILLEGAL
<button class="btn btn-danger delete" onclick="deleteImage("'+type+'");">
results in (alert): 'filename'
<button class="btn btn-danger delete" onclick="deleteImage('" + filename + "');">
results in: Uncaught SyntaxError: Unexpected token ILLEGAL
<button class="btn btn-danger delete" onclick="deleteImage(" + filename + ");">
result in: Uncaught SyntaxError: Unexpected token }
this is the full code (modified, blueimp fileuploader)
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-download fade">
{% if (file.error) { %}
<td></td>
<td class="name"><span>{%=file.name%}</span></td>
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
<td class="error" colspan="2"><span class="label label-important">Error</span> {%=file.error%}</td>
{% } else {
// add the image urls to the file inputbox
var filename = file.name;
var prev = $("#mFile").val();
$("#mFile").val(prev + file.name + ",");
%}
<td class="preview">{% if (file.thumbnail_url) { %}
<img src="modules/mod_stern_form_prijsopgave/upload/server/php/files/thumbnail/{%=file.name%}">
{% } %}</td>
<td class="name">
{%=file.name%}
</td>
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
<td colspan="2"></td>
{% } %}
<td>
<button class="btn btn-danger delete" onclick="deleteImage('" + filename + "');" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}"{% if (file.delete_with_credentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
<i class="icon-trash icon-white"></i>
<span>Verwijderen</span>
</button>
</td>
</tr>
{% } %}
</script>
and testing like this:
function deleteImage(filename) {
alert(filename);
}
what am I doing wrong? Thanks for your advice
try the template format for onclick value:
onclick="deleteImage('{%=filename%}');"
try file.name as well
onclick="deleteImage('{%=file.name%}');"
<button id="deleteOnClick" class="btn btn-danger delete">...</button>
and in javascript:
document.getElementById("deleteOnClick").onclick = function(){deleteImage(filename);}
edit:
if you want to delete the file specified only by the original filename value:
var deleteByFile = (function (filename){
return function(){deleteImage(filename);};
}(filename));
document.getElementById("deleteOnClick").onclick = deleteByFile
You can't access JS variables from your HTML. You must do something like this:
var filename = 'testing';
document.getElementById('testdiv')
.setAttribute('onclick', "alert('" + filename + "')");
filename = 'more testing';
Here is a fiddle.
try to use onclick="deleteImage(" + filename + ");"
You can set a varaiable like var counter = 1;
Wherever it is required, you can update it like
onclick="updateCount('+counter+')"

Categories

Resources