JQUERY: Dynamic AJAX and html element removal - javascript

Consider this code:
<tr>
<td>
<input type="checkbox" name="20081846" value="20081846" class="chk-input">
</td>
<td>20081846</td>
<td>AGONOY, JAY TAN</td>
</tr>
Let's say I have N of these in a table (with different sets of data). What I am planning is, if the user checks the input box, it will delete the users are checked. I got it using this JQUERY
var del_users = function(btn,chk,url) {
$(btn).click(function(){
$(chk).each(function(){
if($(this).attr('checked') == 'checked') {
//pass code data
}
});
});
}
Which works, I just have to do the function that deletes the data.
My next problem is, once the data is deleted, I want the row displayed in the table to be removed in the display. Other than refreshing the entire entries, is there a way to selectively remove the checked "tr" elements?

$(chk).each(function(){
if($(this).prop('checked') === true) {
$(this).closest('tr').remove();
}
});

Removes the row with a nice animation:
if($(this).attr('checked') == 'checked') {
//pass code data
var $row = $(this).closest('tr');
$row.slideUp('fast',function() {
$row.remove();
});
}
You didn't post your ajax code, otherwise I would have added the removal code to the success callback (remember closure though!)

Related

JQuery - Appended Table keeps multiplying itself or duplicating itself when a toggle button is clicked

I wish to have the user click a button to retrieve a table which has data from a mysql database once a button is clicked using an Ajax call using JQuery. The table is appended to a table element which toggles itself for the user to see and disappears once again by clicking a button. This has been achieved from the code below. However, every time the button is clicked, the table multiplies itself and adds two(2) additional copies of itself once it reappears. Which means every time the button is click, it appends itself once again to the table element. I wish that the user on sees the table once when a button is clicked and it disappears again when the same button is clicked again. Once it is clicked for the third time, the same table should reappear and not additional tables.
I have tried the remove method. I have tried the hide and show methods.
<HTML>
<button type = "button" id="allDataTable">Load Stores Table
Data</button>
<br/>
<br/>
<div id="storesT"></div>
<table class='table table-bordered table-striped' id='station_table'>
<JQUERY>
$(document).ready(() => {
$('#allDataTable').click(()=> {
$.ajax({
url:'http://localhost:5000/alldata',
type:'GET',
datatype:'json',
success:(data) => {
//console.log('You received some', data);
var station_data ='';
station_data
+='<tr>'+'<th>ID</th>'+'<th>Station</th>'+'<th>Address</th>'+
'<th>Monthly C-Store Sales</th>'+'<th>Operator</th>'+'<th>Top
SKU</th>'+'</tr>'
$.each(data, function (key,value){
station_data +='<tr><td>'+value.ID+'</td>
<td>'+value.Station+'</td><td>'+value.Address+'</td>
<td>'+value.monthly_cstore_sales+'</td><td>'+value.Operator+'</td>
<td>'+value.Top_SKU+'</tr></td>';
});
$('#station_table').append(station_data);
//NOT WORKING $('#station_table').remove(station_data);
//NOT WORKING $('#station_table').hide(station_data);
//NOT WORKING $('#station_table').show(station_data)
$('#station_table').toggle(station_data);
}
});
});
});
One solution would be to check if the data has already been added to the DOM before making the AJAX call. If not, make the call and then add the data. If yes, then simply toggle a class to hide/show the table.
$(document).ready(() => {
$('#allDataTable').click(()=> {
// Check for the existence of the data table here
if (!$('#station_table').children.length) {
$.ajax({
url:'http://localhost:5000/alldata',
type:'GET',
datatype:'json',
success:(data) => {
//console.log('You received some', data);
var station_data ='';
station_data +='<tr>'+'<th>ID</th>'+'<th>Station</th>'+'<th>Address</th>'+'<th>Monthly C-Store Sales</th>'+'<th>Operator</th>'+'<th>Top SKU</th>'+'</tr>';
$.each(data, function (key,value){
station_data +='<tr><td>'+value.ID+'</td> <td>'+value.Station+'</td><td>'+value.Address+'</td><td>'+value.monthly_cstore_sales+'</td><td>'+value.Operator+'</td> <td>'+value.Top_SKU+'</tr></td>';
});
$('#station_table').append(station_data);
}
});
}
else {
$('#station_table').toggleClass('hide');
}
});
});
CSS
.hide {
display: none;
}
The hide() function hides an element rather than a piece of code. I suggest adding an identifier to each row such as:
station_data +='<tr id="some-identifier"><td>...</td></tr>
You can then toggle the row visibility with
$('#some-identifier').hide() and $('#some-identifier').show()
Check if #station_table is empty first. If so, load content via Ajax. If not, toggle its visibility (if you don't want to reload its contents).
if ($('#station_table').is(':empty')) {
... load content via Ajax ...
}
else {
$('#station_table').toggle();
}

incorrect array push and splice?

I am making an invite system. I am using ajax to load a list of search results. When an li is clicked I push the user's id into an array and append a checkmark to the li to let them know they were added to the list.
The push is working but the splice is not. Also when the list is empty the submit button does not return to its disabled state and original styling.
Lastly, when I search again (re-calling the ajax) it removes the appended checkmark. Is there a way with javascript to store which user was click on and retain the appended checkmark when they search for another name?
(^ when i load the results with ajax i check if a person is invited or not in my db i could do it so if they are already invited a click would delete from table..if not on li click i insert with an ajax and setTimeout on success.. do you think that would be a bad practice?)
Below is my html && script
HTML
<li class='inviteUser'>
<img src='$usersProfilePhoto' alt=''>
<h2>$usersname</h2>
<input type='hidden' value='$otherUserID'>
<span></span>
</li>
$(function(){
var inviteList = new Array();
$(document).on('click', '.inviteUser', function(){
var inviteUserID = $(this).children('input').val();
inviteList.push(inviteUserID)
$(this).children('span').append("<p class='remove'>✓</p>");
if(inviteList.length > 0) {
document.getElementById('imcSubmitButton').disabled = false;
$('#imcSubmitButton').css({'opacity':'1'});
} else {
document.getElementById('imcSubmitButton').disabled = true;
$('#imcSubmitButton').css({'opacity':'0.25'});
}
});
$(document).on('click', '.remove', function() {
inviteList.splice($(this).index(), 1);
$(this).remove();
});
});
The problem is that the indexes in inviteList don't correspond to indexes in the HTML. You should search for the element in inviteList that contains this item's userID, and splice that out.
$(document).on('click', '.remove', function() {
var userid = $(this).parent().siblings("input").val();
var index = inviteList.indexOf(userid);
if (index != -1) {
inviteList.splice(index, 1);
}
$(this).remove();
});
To solve your problem with remembering which users were invited, the code that processes the AJAX responsee can use:
if (inviteList.indexOf(userId) != -1) {
// Add checkmark
}
Things would be easier if inviteList were an object rather than array, using userids as keys.

JQuery show table row if value found

This might seem similar to other questions, and I have found and read through those questions and tried them, but I haven't gotten a working solution as of course, my code is unique and I need maybe another set of eyes to help me find my bug.
Anyway, the problem:
I'm creating a table (with PHP), and essentially if a cell has a value, the row gets an id of 'foo' and is hidden (using CSS - display: none;), and when I click a checkbox I'm trying to display all those hidden rows.
<tr id='foo'><td>this row is hidden</td></tr>
<tr><td>this row is not hidden</td></tr>
My jQuery is currently this:
$("#showHiddenRows").click(function() {
if($(this).is(":checked")) {
alert("showing"); //This pops up
$("#tableName").each(function() {
if($("#tableName").find("tr").attr("id") === 'foo') {
$("#tableName").find("tr").attr("style", "display: initial;");
alert("found a hidden row"); //This does not pop up...
}
});
} else {
alert("hiding");
//essentially the same code here, but display:none;
}
So I added alerts as you can see, the "showing" and "hiding" alerts pop up, but the "found a hidden row" doesn't, implying that searching through my table doesn't find any rows with an ID of 'foo', and I'm not sure why. Is there a better way to do this/is this the best way, and if so what did I do wrong?
Thanks in advance!
Edit: Quick explanation of what I was intending the code to do:
Loop through each row in the tableName table
If you find a tablerow with an ID of 'foo', show or hide the row.
Do not use duplicate IDs; use a CSS class instead. By definition, IDs should be unique; therefore no two or more elements should have the same ID.
HTML:
<tr class='foo'><td>this row is hidden</td></tr>
<tr><td>this row is not hidden</td></tr>
JS:
$(function() {
$("#showHiddenRows").on('change', function() {
if( this.checked ) {
$('table tr.foo').show();
} else {
$('table tr.foo').hide();
}
});
});
Or, you could shorten it like this:
$(function() {
$("#showHiddenRows").on('change', function() {
$('table tr.foo')[ this.checked ? 'show' : 'hide' ]();
});
});
using non-unqiue id with jQuery will cause issues, but I'll leave that with you
here is what you should do to show hidden rows.
$("#showHiddenRows").click(function() {
if($(this).is(":checked")) {
$("#tableName").each(function() {
var table = $(this);
var hiddenRows = table.find("tr[id=foo]").show();
if(hiddenRows.length)
alert("found " + hiddenRows.length + " hidden rows");
});
} else {
alert("hiding");
}
});
Ended up with (thanks to user3558931):
$(function() {
$("#tableName").on('change', function() {
if($(this).(":checked")) {
$('#tableName tr#foo').show();
} else {
$('#tableName tr#foo').hide();
}
});
});

Javascript (jquery) in my rails app is crashing IE

I've got a ruby on rails app where I'm using a table to display some data, and then allowing the user to edit the data in the table by clicking on the row and popping up a form for the relevant data. When changes are made to the form, the appropriate row in the table is updated.
The event listener for the table row click, which displays the appropriate form, looks like this:
$('.addable-rows > tbody').on('click', 'tr', function(e){
e.preventDefault();
var fieldset = $($(this).data('id'));
if ($(this).hasClass('selected')){
$(this).removeClass('selected');
fieldset.hide('slow');
} else {
$(this).siblings().removeClass('selected');
$(this).addClass('selected');
fieldset.siblings().hide('slow');
fieldset.show('slow');
}
});
The listener that checks for changes in inputs on the form and updates the appropriate row in the table looks like this:
$('.addable_row_host').on('change', ':input', function(){
var fieldset = $(this).closest('fieldset')
var id = fieldset.attr('id')
$('#'+id+'_tr').replaceWith(build_row(fieldset, id));
});
The build row method referenced above is:
function build_row(fields, id){
row = $("<tr id='"+id+"_tr' data-id='#"+id+"' class='selected'></tr>");
fields.find('select, input:not([type=hidden])').each(function(){
val = $(this).val();
if(val == null){
val = '';
}else if(val.indexOf(",") !== -1){
val.split(",").join(", ");
}
row.append('<td>'+val+' </td>');
});
return row;
}
This all works and is quite lovely in Chrome/FF/Safari, but it causes IE to grash most ungracefully. IE pops up a window reporting a crash and reloads the page. No mention of what caused the problem in the console. Additionally, any and all debugging statements in this code runs and is displayed to the console before the crash, so I haven't been able to pinpoint where it's happening.
Anyone know what I'm missing?

jQuery check all not working on checkboxes

I'm writing some code that will allow the following:
1.) If a user checks a checkbox it will change the parent <tr> to have a class of selected (this can also be unchecked and remove the class)
2.) Any checkboxes that are already checked will have the class added on document load
3.) If a user checks the #checkall input then all inputs will become checked and add the class of selected (if checked again then it will unselect all and remove the class)
This is the code I have so far:
$("table input[name=choose]:checked").each(function()
{
$(this).closest("tr").addClass("selected");
});
$("table input[name=choose]").live("change", function()
{
$(this).closest("tr").toggleClass("selected");
});
if ($('#checkall:checked') == true)
{
$('#checkall').live("click", function()
{
$('table input[name=choose]').attr('checked', false);
$('table input[name=choose]').closest("tr").toggleClass("selected");
});
}
else
{
$('#checkall').live("click", function()
{
$('table input[name=choose]').attr('checked', true);
$('table input[name=choose]').closest("tr").toggleClass("selected");
});
}
The first two work fine but number 3 doesn't uncheck the checkboxes... Any ideas why? But the class part works fine??
Thanks
I guess it runs always into the else block (have you debugged this)?
Try writing this for checking if the checkbox is checked:
if ($('#checkall').attr('checked'))
Because if ($('#checkall:checked') == true) is always false..
either use
if ($('#checkall').is(':checked'))
or
if ( $('#checkall:checked').length )
Update after comment
Replace the entire third part (all the if/else) with
$('#checkall').live("change", function()
{
$('table input[name=choose]')
.attr('checked', this.checked)
.closest("tr")
.toggleClass("selected", this.checked);
});
demo at http://jsfiddle.net/gaby/KqwsZ/1/

Categories

Resources