The idea for this page is to load the 'skills' from my java application and dynamically create a Delete button that allows me to delete those 'skills' from the application.
Error received when attempting to click the button to delete a skill.
manageTech:1 Uncaught ReferenceError: deleteMe is not defined at
HTMLButtonElement.onclick (manageTech:1)
js file:
$( document ).ready( () => {
var url = window.location;
// GET REQUEST
$("#btnGetFiles").click( (event) => {
event.preventDefault();
ajaxGet();
});
function deleteMe(id) {
window.alert("Button clicked, id " + id + ", text");
$.ajax({
url: '/api/technologyList' + '/' + id,
type: 'DELETE',
success: function() {
ajaxGet();
}
})
}
// DO GET
function ajaxGet() {
$.ajax({
type: 'GET',
url: '/api/technologyList',
success: function (skills) {
$.each(skills, function (i, skill) {
$('#listFiles').append('<tr>' + '<td>' + '<button ' +
'type="submit" ' +
'data-id="' + skill.id + '" ' +
'onclick="deleteMe('+skill.id+')"' +
'name="deletebtn">' +
'Delete' +
'</button>' + '</td>' +
'<td>' + skill.id + '</td>' +
'<td>' + skill.logo + '</td>' +
'<td>' + skill.techName + '</td></tr>')
})
}
});
}
});
Your deleteMe is not on the top level - it's inside your $( document ).ready( () => {, so it's not a global variable, so the inline handler onclick="deleteMe('+skill.id+')" fails. (Inline handlers can only reference global variables on the top level.)
Although you could fix it by moving deleteMe outside, inline handlers are bad practice; consider attaching an event listener properly using Javascript instead. Remove the inline handler, and use event delegation:
$('#listFiles').on('click', 'button[name="deletebtn"]', function() {
deleteMe(this.dataset.id);
});
Related
EDIT (done): I figure it out. Syntax is <button onclick="editItem('+data[i].id+')">EDIT</button>'
I have this, it generates all the objects in database, showing id, name and actions - both buttons have different onclick function where i want to send object id for future things.
I just need an answer how to put data[i].id in '<button onclick="editItem(ID)">EDIT</button>', which syntax?
$.ajax(
{
type:'GET',
url:'api',
dataType: 'json',
success: function(data){
console.log(data);
for (var i=0; i<data.length; i++) {
var row = $(
'<tr>' +
'<td>' +
data[i].id +
'</td>' +
'<td>' +
data[i].name +
'</td>' +
'<td>' +
' <button onclick="editItem(ID)">EDIT</button>' +
' <button onclick="deleteItem(ID)">DELETE</button>' +
'</td>' +
'</tr>'
);
$('#my_table').append(row);
}
}
}
);
I'd be more inclined to add the ID to the buttons as data-attributes and use a delegated event handler to handle the clicks
// Set up event handlers on your table to listen for button clicks
const table = $("#my_table")
.on("click", "button[data-edit]", function(e) { // EDIT button
const id = this.dataset.edit
// and so on, eg...
editItem(id)
})
.on("click", "button[data-delete]", function(e) { // DELETE button
const id = this.dataset.delete
// and so on, eg...
deleteItem(id)
})
// Using jQuery's DOM helpers makes for more concise code IMO
$.getJSON("api")
.done(data => table.append(data.map(({ id, name }) =>
$("<tr>").append([
$("<td>", { text: id }),
$("<td>", { text: name }),
$("<td>").append([
$("<button>", { text: "EDIT", "data-edit": id }),
$("<button>", { text: "DELETE", "data-delete": id })
])
])
)))
I am using ajax and dynamically manipulating <td> elements inside success returning of data using java script.
I have tried and everything is running fine , I am getting data inside my <td> elements but unfortunately can not handle how to put anchor tag inside some <td> elements as those returning data containing some files that is present on server folder so I need to make anchor tag so that user can open the file .
$("#Status").on('change', function () {
$("#Table11").find("tr:not(:first)").remove();
debugger;
var Status = $("#Status").val();
$.ajax({
url: '/BusinessCaseProcess/GetRec',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { Status: Status },
success: function (response) {
debugger;
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.Title + '</td><td>' + item.EmployeeName + '</td><td>' + item.Department + '</td><td>' + item.SubDepartment + '</td><td>' + item.Station + '</td><td>' + item.DateOfRequest + '</td><td>' + item.TrackingID + '</td><td>Primary </td><td>Secondary </td><td>' + item.HeadOfDepartmentStatus + '</td><td>' + item.HRMStatus + '</td><td>' + item.HeadOfITStatus + '</td><td>' + item.FinanceControllerStatus + '</td><td>' + item.VPPStatus + '</td></tr>';
});
$('#Table11').append(trHTML);
}
})
As you can see i am trying to make anchor tag inside td elements in code. The variable is containing the file name , and inside href i am giving folder name , i need to open the file on click just like anchor tag does.
I using a code on my page. Like this:
$('#language_id').change(function () {
var urli = 'https://example.com/php/get_arch.php?language_id=' + language_id;
$.ajax({
type: "GET",
url: urli,
dataType: 'json',
success: function(response){
var options = '';
$.each(response.archs, function() {
options += '<option value="' + this.arch_id + '">' + this.name + '</option>';
});
$('#arch_id').html('<option value="0">- ' + selachitecture + ' -</option>'+options);
$('#arch_id').attr('disabled', false);
}
});
});
$('#arch_id').change(function(){
var version_id = $('#version_id :selected').val();
$('#selectBoxInfo').load('https://example.com/dl.php?fileName=' + arch_id + "&lang=" + lang);
return(false);
});
$('body').on('click', '.buttond a', function() {
alert("new link clicked!");
$("a").removeAttr("onclick");
});
I explain my code: when selecting an optional, it will create a button "Download". This button load by Ajax. I don't want feature pop-up of this button.
So, I tried to prevent this button turn on the pop-up.
The problem is: at first click in button, my Javascript is not working. It only works from the second click.
I don't know problem at here. I using 'on' to listen to all event.
replace your code with this code ..
$('#selectBoxInfo')
.load('https://example.com/dl.php?fileName=' + arch_id+"&lang="+lang
,function(){
$("a").removeAttr("onclick");
}
);
I have been working on a e-commerce web application. There is a wishlist module which I'm trying to implement. I'm adding the products into wishlist using ajax calls and also removing it with ajax. The adding part works fine but I have a problem in removing part . What I'm trying to do is, making an ajax call to fetch the wishlist items from the database and adding a remove button dynamically using jquery. Although I know that I have to use a .live function to attach an event to it which I did but when i click on the button all the items which are present in the wishlist are removed . I see multiple ajax request was made in console under network tab and I don't get it why , although I clicked it only once. The following is a snippet of my code
$.ajax({
type: "POST",
url: "fetchdata1",
data: "cat=" + cat,
success: function(data) {
productContainer.innerHTML = "";
var $productContainer = $('#productContainer');
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span>\n\
<br/><br/><a id='remove' href='#'>REMOVE</a></div>");
foo(value['id']);
} else {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span></div>");
}
});
}
});
function foo(value) {
var pid = value;
$('#remove').live("click", function() {
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
In the first ajax request I'm fetching products from the database then adding remove button to it dynamically then calling function foo which attach the click event using .live function and then make call to database to remove it.
Hey guys I'm not pro at web, so go easy on me if I made some silly mistake.
Thanks!
Problem:
You have same id for multiple hyperlink and you are using .live function on "id based" selector. It is applying click function again & again on first element.
Solution:
Update your hyperlink
<a href='#' onclick="foo(this)" pid=value['id']>REMOVE</a>
Then in foo() function
function foo(obj) {
var pid = $(obj).attr("pid");
$(obj).bind("click", function() {
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
i don't get why you using same id multiple times.
and afaik, jQuery.live already deprecated.
you can use this if you want to get live behavior:
$(document).on('click', 'element-selector', function(){
...
});
with your code, it can rewriten to:
$(document).on('click', '[id=remove]', function(){
...ajax call...
});
now the problem with your fetch data function is this:
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
...append element...
**foo(value['id']);**
} else {
...append element...
}
});
as we know foo() are your function that bind remove behavior.
based on your code, whenever that fetch data has newVar = 1, it will directly call foo. which mean binding remove behavior multiple times, as many as newVar = 1 was.
solution:
you can put pid as a attribute on your a element
maybe something like remove
and within remove click function, you can use $(this).attr('pid') to get that value.
and remove that foo() content to outside the function, since $(element).live(...) or $(document).on(event, element, ...) will listen the element, even the element dynamicly added to the page.
The issue happened because you register listener multiple times in each loop. So to resolve, you need to register once after all button has been populated. I also change selector to class ".remove" because you going to have multiple remove button so using id is will be duplicated, and using jquery .on() instead of .live() (deprecated)
$.ajax({
type: "POST",
url: "fetchdata1",
data: "cat=" + cat,
success: function(data) {
productContainer.innerHTML = "";
var $productContainer = $('#productContainer');
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span>\n\
<br/><br/><a class='remove' id='remove' data-pid='" + value['id'] + "' href='#'>REMOVE</a></div>");
} else {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span></div>");
}
});
foo();
}
});
function foo() {
$('.remove').on("click", function() {
var pid = $(this).data("pid");
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
I have a javascript function, for example:
function SuperTD(id,str,tooltip) {
return '<td id="' +id+ '" title="' +tooltip+ '">' +str+ '</td>';
}
The SuperTD called and concatenated with many elements, and I don't want to change how it works (into generating element without using html string).
And I need to trigger a function when that elements are rendered, for example:
function SuperTD(id,str,tooltip) {
var onwhat = 'onwhat="executeFixedFunction(' + "'" +id+ "'" + ')"';
return '<td><div id="' +id+ '" title="' +tooltip+ '" ' +onwhat+ '>' +str+ '</div></td>';
}
where executeFixedFunction is:
function executeFixedFunction(id) {
$('#' + id).uploadFile({
url:"/file/upload"
});
}
what the correct event to do this? I need to initialize a file-upload element everywhere SuperTD called
The users still using Firefox 3.5.
EDIT more context:
GridBuilder.render = function() {
// return from cache
var html = '';
// calls html += SuperTD( ... )
return html;
}
GridBuilder.renderTo = function(id) {
$('#'+id).html(this.render());
// I guess this is where I should initialize the file upload, but still, is there another way?
}
If you are already using jquery i would consider doing it this way:
function superTD (id, str, tooltip) {
return $('<td/>', {
id: id,
title: tooltip,
text: str
}).uploadFile({
url: '/your-url'
})
}
Then you can call appendTo method on superTD to insert it into table row
You can use a setTimeout function to delay the callback function.
function SuperTD(id,str,tooltip) {
var onwhat = 'onwhat="executeFixedFunction(' + "'" +id+ "'" + ')"';
setTimeout(function(){ executeFixedFunction(id) }, 1000);
return '<td><div id="' +id+ '" title="' +tooltip+ '" ' +onwhat+ '>' +str+ '</div></td>';
}
Everything put together with slightly modified Jakubs suggestion. See on Plunkr.
function superTD(id, str, tooltip, callback) {
var td = $('<td/>', {
id: id,
title: tooltip,
text: str
});
var up = $('<span/>'); // <-- this elm will be replaced
td.append(up);
$('#container').append(td);
callback(up, str);
}
function onCreated(elm, fname) {
elm.uploadFile({
url: '/url',
fname: fname
});
}
$(document).ready(function() {
superTD(1, 'foo', 'bar', onCreated);
superTD(2, 'bar', 'foo', onCreated);
});