JQuery / Javascript Click Event not detected in Dynamic table - javascript

I have looked through several answered questions, and tried to implement the solutions for my issue. I have a table being generated dynamically in javascript, that I then need a click event on in one column for each row.
I have tried the following:
$("#iFaceTbl tr").on('click', 'td.delInt', function(event) {
console.log("Clicked.");
let intId = event.target.id;
console.log("ID was: " + intId);
});
Wehre delInt is a class on the cell in each row.
When I run it, and watch the console, no click event is detected at all.
I'm sure I've done something wrong. For reference, here is the html, and javascript forming the table.
<table id="iFaceTbl"></table>
and
for (i=0; i < iFaces_count; i++) {
let html_to_insert = '<tr><td>' + intArray[i] + '</td><td id="' + intArray[i] +'" class="delInt"><i class="fa fa-trash delInt" aria-hidden="true"></span></td></tr>';
Currenthtml = Currenthtml + html_to_insert;
if (i == iFaces_count-1) {
iFaceTbl.innerHTML = Currenthtml;
}
}
Any help is greatly appreciated.

Was able to solve my issue with the change shown here to my event trigger. I had to remove the icon portion in favor of a 'X'. Code now looks like this:
$(document).on('click', '#iFaceTbl td', function(event) {
console.log("Clicked.");
let intId = event.target.id;
console.log("ID was: " + intId);
});

Related

JQuery: Text changed on previous element disappears

I am working on a JQuery application where I am trying to change the text of a previous element using $(element).prev().text("Mytext");. But when I scroll up / scroll down the page, the changes I have made are disappeared.
titles = $('.checkGroup:checked').parent().map(function () {
return $(this).text();
}).get(); // Generate Array of Titles
for (i = 0; i < titles.length; i++) {
$('span[level ="' + i + '"]').prev().text(titles[i]);
}
this is my code snippet. please help me to fix this
To fix this add the following JS.
Note that this is a quick fix. There must be some callback functions you can use to have the same end effect. The Slick.Grid plugin is rendering the HTML on scroll. Hence the issue.
Events for SlickGrid.
Edit 1:
grid.onScroll.subscribe(function(e,args){
$('.checkGroup:checked').parent().each(function (i, val) {
$('span[level ="' + i + '"]').each(function(){
$(this).prev().text($(val).text());
});
});
})
Normally the following might have worked. But the SlickGrid had many mysteries of its own. Its not a scroll event.
$(document).on('scroll', '.slick-viewport',function(){
$('.checkGroup:checked').parent().each(function (i, val) {
$('span[level ="' + i + '"]').each(function(){
$(this).prev().text($(val).text());
});
});
})

Unable to remove tr in a table using jquery

so I am having a problem in removing a particular tr in table using jquery.
So this is the scenario:
I have a table in which rows where clickable. And when I clicked one of them, I will be able to update the object data associated with that row. However, after updating the object, I want to reflect the changes in the td's of that particular tr.
My solution is, to remove the old tr and replace with the new tr. However, It did not remove the old tr instead just inserted the new tr. So this is my code:
function update_table_after_updating(selected_violator){
violators_table.find('tr').each(function (i, el) {
var tr = ($(this));
var td_text = $(this).find('td:first').text();
if(td_text == selected_violator.violator_id){
console.log(tr);
//I cant remove this row
tr.remove();
return false;
}
});
update_table(selected_violator);
}
The update_table() function
function update_table(violator){
var img_str1 = '<img class=\"obj-pic\" src=\"' + Main.Vars.base_path + violator.front_temp_file_path + '\">';
var img_str2 = '<img style=\"margin-left: 10px;\" class=\"obj-pic\" src=\"' + Main.Vars.base_path + violator.rear_temp_file_path + '\">';
var img_str3 = '<img style=\"margin-left: 10px;\" class=\"obj-pic\" src=\"' + Main.Vars.base_path + violator.right_temp_file_path + '\">';
var img_str4 = '<img style=\"margin-left: 10px;\" class=\"obj-pic\" src=\"' + Main.Vars.base_path + violator.left_temp_file_path + '\">';
violators_table.dataTable().fnAddData([
violator.violator_id,
violator.get_full_name(),
'Under Construction',
img_str1 + img_str2 + img_str3 + img_str4,
]);
$('#violators_tbl tbody tr').on('click', function(){
var td = $(this).find('td:first').text();
//returns violator object
selected_violator = get_violator(td);
show_modal('view_violator');
});
}
Thank you very much! Your responses will be greatly appreciated.
PS: I am using jquery DataTables.
Well this is kinda disappointing, I have searched through Jquery Docs then I have find this:
.empty() -> This method removes not only child (and other descendant)
elements, but also any text within the set of matched elements. This
is because, according to the DOM specification, any string of text
within an element is considered a child node of that element. Consider
the following HTML:
Unlike remove(). empty() also removes child nodes of the selected element.
And, voila! The tr has been removed.

Jquery add more with html object

I am trying to make addmore functionality with jQuery html object below is the code.
var addmorehtml = $("<div><div class='btndiv'><label>Category Name : </label><input type='text' name='catname[]'></div></div>");
var HTML = addmorehtml;
var clickcount = 1;
$('button#addmore').on('click', function(){
HTML.find('div.btndiv').wrap("<div id='so_" + clickcount + "'></div>");
$("<button class='removeme' onClick='removeMe(\"" + clickcount +"\")'>Remove Me</button>").insertBefore(HTML.find('div.btndiv'));
$('div#result').append(HTML.html());
/* Why do I need to do this two steps START */
HTML.find('div.btndiv').unwrap("<div id='so_" + clickcount + "'></div>");
HTML.find('button.removeme').remove();
/* END */
clickcount++;
});
If I don't unwrap the added html at the end, it keeps on adding to new elements created. I know there are many ways of doing add more but if I want to go with this what modification in existing code should be done so that I don't need to perform those those steps as mentioned in between comments.
Any help would be appreciated.
Fiddle link : http://jsfiddle.net/bhingarde/Lav7Lt7o/13/
JSFIDDLE DEMO -> http://jsfiddle.net/Lav7Lt7o/18/
You just wanted a modification to your existing code but I wanted to give you another answer which is better than the modification answer I have posted before this.
The below answer removes the usage of clickcountand uses event delegation to capture the remove event.
$('button#addmore').on('click', function() {
var addmorehtml = $("<div id='so'><button class='removeme'>Remove Me</button><div class='btndiv'><label>Category Name : </label><input type='text' name='catname[]'></div></div>");
$('div#result').append(addmorehtml);
});
$(document).on('click', '.removeme', function() {
$(this).parent('#so').remove();
});
JSFIDDLE DEMO -> http://jsfiddle.net/Lav7Lt7o/15/
As shown below, add the html blob directly to the div#result instead of breaking it.
var clickcount = 1;
$('button#addmore').on('click', function() {
var addmorehtml = $("<div id='so_" + clickcount + "'><button class='removeme' onclick='removeMe(" + clickcount + ")'>Remove Me</button><div class='btndiv'><label>Category Name : </label><input type='text' name='catname[]'></div></div>");
$('div#result').append(addmorehtml);
clickcount++;
});
function removeMe(id) {
$('div#so_' + id).remove();
}

Change link attribute after calling function

In a Jquery Mobile application I have a listview that calls a function wen clicked:
Go home
When a row link as above is clicked it calls this function:
function OnSaveOrDelete(acID){
if (localStorage.Favourites.indexOf("/" + acID + "/") >= 0)
{
alert('Ac Removed #' + acID);
$(this).prop('data-icon','delete');
var tmp = localStorage.Favourites;
localStorage.Favourites = tmp.replace("/" + acID + "/", "");
}
else{
alert('New Ac Saved #' + acID);
localStorage.Favourites += "/" + acID + "/";
}
}
When the existing item isnt in localStorage I add it, and then need to change the icon / data-icon attribute. As is shown in my code above, Im trying to do this via:
$(this).prop('data-icon','delete');
Ive also tried:
$(this).attr('data-icon','delete');
But neither of these work. Im assuming this is because '$(this)' isnt defined.
How can I updated my code to do what I need?
You can pass this in:
onclick="OnSaveOrDelete(' + item.ID + ', this)"
function OnSaveOrDelete(acID, obj) {
//$(obj) refers to the clicked element
$(obj).prop('data-icon','delete');
}

Multiple buttons with the same ID [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
SOLVED: Not enough coffee - the event listener was being added before the buttons were created.
Im creating a table from HTML LocalStorage like so:
for (i = 1; i <= localStorage['count']; i++) {
tableHtml = tableHtml + "<tr><td><button class='delete' id=" + i + ">Delete</button></td><td>" + localStorage['fullName' + i] + "</td><td>" + localStorage['email' + i] + "</td><td>" + localStorage['phoneNum' + i] + "</td></tr>";
}
This works great, however the delete button is proving troublesome.
I saw this:
jQuery find ID of clicked button by class
So I assumed i could do this:
$(".delete").click(function () {
alert('delete clicked for id: ' + $(this).id);
});
However, it doesn't work. Suggestions?
you can get the id of element by using javascript without using jquery wrapper like this:
$(".delete").click(function () {
alert('delete clicked for id: ' + this.id); // get id via javascript
});
or:
$(".delete").click(function () {
alert('delete clicked for id: ' + $(this)[0].id); // via javascript object
});
If you see the link reffered in question it is also getting id using javascript (this.id)
if you want to get via jquery then:
$(".delete").click(function () {
alert('delete clicked for id: ' + $(this).attr("id")); // via jquery object
});
When are you binding the click event? If it's before the element exists, you'll want to use .on.
$('body').on('click','.delete', function(){
alert('delete clicked for id: ' + $(this).attr('id'));
});
Check out a working jsFiddle.
use pure javascript:
this.id
or jquery
$(this).attr('id');
as $(this) is jquery object. and you are trying to get javascript property id. You need to first convert the object to javascript.
$(this)[0].id;
DOM elements shouldn't have numbers as the first character of id.
Change your code to something like this:
for (i = 1; i <= localStorage['count']; i++) {
tableHtml = tableHtml + "<tr><td><button class='delete' id=del-id" + i + ">Delete</button> </td><td>" + localStorage['fullName' + i] + "</td><td>" + localStorage['email' + i] + "</td><td>" + localStorage['phoneNum' + i] + "</td></tr>";
}
And
$(".delete").click(function () {
alert('delete clicked for id: ' + $(this).prop('id');
});
This should take you on the right track.
REMEMBER that .prop() function is jQuery 1.10+ specific.
If you are using an older version use .attr()
As some people here mentioned - id's can be numeric as of HTML5
still using them in a numeric form might generate rather unpleasant problems.
Link in the comments below from one of the users.

Categories