Jquery delete elements that were created using .after - javascript

I have a table in my html file which has the column header hard-coded:
<table id="debugger-table">
<tr>
<th>Attribute</th>
<th>Computed</th>
<th>Correct</th>
</tr>
</table>
Which I populate with values for row 2 onwards in a .js file using jquery:
tableString = '';
DEBUG_DATA.forEach(function(debug_line){
tableString += '<tr><td>' + debug_line['attribute'] + '</td><td>' + debug_line['computed'] + '</td><td>' + debug_line['correct'] + '</td>'
});
$('#debugger-table tr:last').after(tableString);
When the user performs a certain action I want to update the values. My question is how do I remove the text I've added, so that I can replace it with new text, instead of just appending the new values after the old ones.
I figure I could destroy the whole table and then create a new one with the column headers. Seems overkill though. Is there a way to refer back to the text added with .after, and delete it? thanks.

Store the addition into a jQuery object:
const rows = $(tableString);
('#debugger-table').append(rows); // Tip: this is better than
// $('#debugger-table tr:last').after(rows);
Then later remove it when needed:
rows.remove();

Related

Enable/Disable an HTML Element With Dynamically Generated Names/Tags

I have a table in HTML where the ID is dynamically generated from a row counter:
$(table).find('tbody').append("<tr>name=\"tableRow\"</tr>"
+ "<td>"
+ "<select id=\"shapeSelect_" + rowCount + "></td>"
+ "<option onclick=\"sphereSelect()\" value=\"sphere\">Sphere</option>"
+ "<option onclick=\"cylinderSelect()\" value=\"cylinder\">Cylinder</option>"
+ "</select>"
+ "</td>"
+ "<td><input type=\"text\" id=\"altitude" + rowCount + "\"</td>"
+ "<td><input type=\"text\" name=\"maxAlt\" id=\"maxAltitude_" + rowCount + "></td>"
+ "</tr>"
I need maxAltitude to become disabled for input when sphere is selected. When cylinder is selected, it should become enabled for input.
Every example I find is pretty simple but requires knowing exactly what the ID is, where in my code it is dynamically generated. This is an example of what I'm finding:
$(#maxAltitude).prop("disabled", true);
How can I do this when maxAltitude will be something more like: maxAltitude_10? There may be 1-n rows in a table, and I need to specifically disable the max altitude in the row where the dropdown select was changed.
I've tried jQuery and javascript but can't seem to find a good way to do this:
<option onclick="shapeSelect()" value="sphere">Sphere</option>
<option onclick="shapeSelect()" value="cylinder">Cylinder</option>
function shapeSelect() {
var shapeSelects = document.getElementsByName("shapeSelect");
var maxAlts = document.getElementsByName("maxAlt");
for(var i = 0; i < shapeSelects.length; i++) {
switch(shapeSelects[i].value) {
case "sphere":
maxAlts[I].disabled = True;
break;
case "cylinder":
maxAlts[i].disabled = False;
}
}
}
With the above code I get: SyntaxError: unexpected token: identifier whenever shapeSelect() is fired.
I've modified the code as follows:
<table class="myTable" id="myTable"></table>
$(table).find('tbody').append("<tr>name=\"tableRow\"</tr>"
+ "<td>"
+ "<select id=\"shapeSelect_" + rowCount + "></td>"
+ "<option value=\"sphere\">Sphere</option>"
+ "<option value=\"cylinder\">Cylinder</option>"
+ "</select>"
+ "</td>"
+ "<td><input type=\"text\" id=\"altitude_" + rowCount + "\"</td>"
+ "<td><input class=\"maxAltitudeInput\" type=\"text\" id=\"maxAltitude_" + rowCount + "\" disabled></td>"
+ "</tr>"
$('#myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
}
And still nothing happens when I change the shape selector dropdown.
EDIT:
Apologies on the naming mismatches. My dev machine is on an airgapped network and I was hand jamming the post here on Stack Overflow. The rowCount variable was being created and incremented in another function. I was trying to only put relevant code in the post for brevity.
I was missing a class from shapeSelector. That was the missing link. It works now!
jQuery actually makes this really easy by binding this to whichever element triggered an event.
For instance, instead of writing a generic function for when that value changes, you could use jQuery to bind an event listener to them:
$('#myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
}
You'll notice a few things in this snippet:
The element we are binding the listener to is the table, not the individual row. That's because the row is dynamic, and we don't want to have to keep adding listeners every time we add a row. Instead we add it to the parent which is stable, but then we specify that we are interested in its children that match ".shapeSelector"
The listener relies on class names, not IDs, since we want to match multiple copies of them, not just a specific one. So you'd need to add those class names or a similar way of matching more than one item
Inside the callback function that runs, you'll notice a couple uses of this. jQuery has bound that to the element that triggered the event listener, in this case, the <select> control. So when we use this, we have to think of it from that perspective. We can get its value by $(this).val(), we can find its parentt with $(this).parent(), etc. In this case, I'm travelling up to the nearest tr, then from there down to that tr's input that I want to disable. You'd need to adjust a little depending on your dom.
Also note that this is a DOM element, not a jQuery result. That's why when we want to run more jQuery commands on it, we have to put it in $() again.
That's how I'd approach it. We don't have your entire code here, so you'll have to adjust a bit, but hopefully that pushes you off in the right direction.
EDIT
To be honest, there were a lot of naming mismatches and things that didn't line up. For instance, you were attempting to append onto a tbody tag, but that tag didn't exist. You were using a rowCount variable, but didn' ever set that up or increment it. The select tag sill didn't have the class name you were trying to use.
I suggest you look at your code piece by piece, ask yourself what you're telling the browser to do, and then do that instruction in your mind to make sure the computer can do it.
HTML:
<table class="myTable" id="myTable"><tbody></tbody></table>
JavaScript:
var rowCount = 0;
function addRow(){
$('.myTable tbody').append(`<tr name="tableRow">
<td>
<select class="shapeSelector" id="shapeSelect_${rowCount}">
<option value="sphere">Sphere</option>
<option value="cylinder">Cylinder</option>
</select>
</td>
<td><input type="text" id="altitude_${rowCount}" /></td>
<td><input class="maxAltitudeInput" type="text" id="maxAltitude_${rowCount}" disabled></td>"
</tr>`);
rowCount++;
}
$('.myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
});
addRow();
addRow();
addRow();
https://jsfiddle.net/32vnjq81/

append a button with a link for each row

I'm new to JavaScript so excuse me for this question,,
when i use jQuery to append data from firebase to a table
i want to append a button but has a href url from variable
url_val = is a variable url i want when i click to the button go to website
$("#data").append("<tr><td>" + title_val + "</td><td><button class='box'> " + url_val + "</button></td></tr>");
i was trying to do the fowling
$("#data").append("<tr><td>" + title_val + "</td><td> <button class='box'> " + GO + "</button></td></tr>");
but i cant add a variable inside
is there a solution for this
I think you've made two mistakes, the first is not using + to concantate strings appropriately as mentioned by #Taplar and #abney317.
Secondly you have unnecessarily taken 'GO' out of your hard coded string, but also not stored it as a variable or concatenated it appropriately.
I have fixed both of these and provided a demonstration.
Let me know if you were hoping for something else.
Demo
// Add click event to add row
$("#addRow").click(function() {
// Store variables
title_val = "Title";
url_val = "www.google.com";
// Append data
$("#data").append("<tr><td>" + title_val + "</td><td> <button class='box'>GO</button></td></tr>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="data">
</table>
<button id="addRow">Add Row</button>

How to prevent appending multiple times in the table, Once It forcing to double click multiple times the table row using Jquery?

I have module appending the result of response to the other table. looking forward I found a solution in my module. however I found problem on that i will give to you guys the scenario what the problem it does.
First Scenario:
User will choose what condiment he wanted to click, Looking forward Ex. User 1 choose the Second table row, the Condiments *LG FRIES.
Second Scenario:
In the first scenario user choose the *LG FRIES, as you can see here modal will open and the result of response will append to the table B.
Third Scenario: Well First and Second scenario look works and good, but here I will show you, how does appending will multiply in the table once i force double click the table row of *LG FRIES.
So now i will let you show my codes.
This is my function for getting the result of clicking the of table row then the result will append to the table B.
$('table#noun_chaining_order').on('click','tr.editCondiments',function(e){
var allow_to_open_condiments_conditional = $(this).closest("tr").find(".allow_to_open_condiments_conditional").text();
if(allow_to_open_condiments_conditional == 'Yes') {
$('.conditional_table_hidden_noun').hide();
$('.conditional_table_hidden_condiments').show();
$('table#noun_chaining_order tr').removeClass('selected');
$(this).addClass('selected');
var find_each_id_condiments = $(this).find('td.condi_section_id').text();
$("table#customer_table_update_chain_order tbody").html('');
$('#customer_modal_update_chain_order').modal('show');
$.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 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#customer_table_update_chain_order tbody').append("<tr class='edit_condimentsClicked' style='font-size:14px; border:none;'><td class='edit_condimentsScreenNameClicked'>" + cat_condi_screen_name + "</td><td class='edit_condimentsScreenPriced'>" + cat_condi_price + "</td><td>"+image+"</td></tr>");
});
},
error:function(response){
console.log(response);
}
});
}
else
{
}
});
So the question will be, How to stop appending multiple times once I force double click the table row?
I see simple solutions here.
When you appending cart item, you can add that item ID from database
to the element. And before appending check if an item from response
doesn't exist in BODY.
Another solution will be just after you click append - hide that CTA
(button)to prevent it from another click.
Check your database for multiple records.
Anyways, please check when you do ajax request? after click?
Have you tried to debug your code with breakpoints? or console?

Append to end of a div through Jquery

I have this div which has a table and i want to add a row to that table dynamically based on a scenario. how this can be done with jquery ?
<div style="margin-bottom: 4px;" id="div_outgoing_call_dates_rows">
<table id="tbl_dynamic_call_dates">
<tbody><tr><td>Appointment date</td><td>Client time window</td></tr>
<tr id="client_app_0"><td>04/10/2013</td><td><select name="CSSAtapsClient[client_time_window_arr][0]" id="client_time_window_0">undefined<option value="5702">07am - 10am</option><option value="5703">10am - 1pm</option><option value="5704">12pm - 3pm</option><option value="5705">03pm - 06pm</option><option value="5706">06pm - 09pm</option><option value="5707">07pm - 10pm</option><option value="5708">09pm - 12am</option><option value="5709">12am - 7am</option></select></td>
</tr>
</tbody>
</table>
</div>
I tried this and it didint work at last row instead adds inside the div and old contents gets cleared.
$("#div_outgoing_call_dates_rows").append(dynamicRow);
Appreciate an early response.
Fiddle Here
EDIT 2
$.each(array,function(i){
if($("#client_app_tr_" + array[i]).length == 0) {
console.log("yes not exisit so adding a new one");
dynamicRow += "<tr id=\'client_app_tr_" + array[i] + "\'><td>" + array[i] + "</td><td>" + "<select id=\'client_time_window_" + i + "\' name=\'CSSAtapsClient[client_time_window_arr][" + i + "]\'>" + dynamicDD + "</select>" + "</td></tr>";
}
});
I have tr id's like this -> client_app_tr_07/10/2013, client_app_tr_08/10/2013, client_app_tr_09/10/2013 ... so if that id is not there i need to add a new row. it doesnt work because the way i am checking it always goes inside this loop. if($("#client_app_tr_" + array[i]).length == 0) {}
EDIT 3
This also doesnt seem to be working. i must be missing something or isnt there any way to check weather a element id exisit or not in jquery ?
if($("#client_app_tr_" + array[i])[0] !== true) {}
Try this, this will help you.
var old_item =$('#div_outgoing_call_dates_rows').html();
old_item=old_item+'New Content';
$('#div_outgoing_call_dates_rows').append(old_item);
Fiddle here.
div_outgoing_call_dates_rows is the div element, you need to append the row to the table inside the div, so use the descendant-selector
$("#div_outgoing_call_dates_rows table").append(dynamicRow);
You must select table in order to append a dynamic row, so change selector:
$("#div_outgoing_call_dates_rows table").append(dynamicRow);

show js array in html table

I have a javascript array and I want to show parts of it in HTML.
For example what html code would I use in the body to show a table of just the info from QR4 - the number and the country? There are other parts to the array so to show the whole QR4 array would be fine, but Id also like to know how to select specific parts
QR4[25] = "China";
QR4[24] = "39241000";
QR8[25] = "China";
QR8[24] = "39241000";
QR8L[25] = "China";
QR8L[24] = "39241000";
QR4L[25] = "China";
QR4L[24] = "39241000";
I have this code making a table in php using csv which works fine but I want it client side, not server side. A table like this would be fine...
<?php
echo "<table>\n\n";
$f = fopen("csv.csv", "r");
while (!feof($f) ) {
echo "<tr>";
$line_of_text = fgetcsv($f);
echo "<td>" . $line_of_text[10] . "</td>";
echo "<tr>\n";
}
fclose($f);
echo "\n</table>";
?>
Here is a really simple example of how you could do it.
Check this fiddle.
You have to pass an array to the function displayArrayAsTable(). You can then specify the range of the array to insert into the table, for example from 24 to 25 like you asked, otherwise all the array will be processed.
The function will return a table element you can then append where you find more appropriate, or tweak the function so that will always insert it for you where you want.
To show all rows of the QR4 array in a HTML table use this:
<table>
<tr>
<th>ID</th>
<th>City</th>
</tr>
<script type="text/javascript">
for(id in QR4)
{
document.write('<tr><td>' + id + '</td><td>' + QR4[id] + '</td></tr>');
}
</script>
</table>
To show specific elements from the Javascript array in a HTML table use this:
<table>
<tr>
<th>Number</th>
<th>City</th>
</tr>
<script type="text/javascript">
document.write('<tr><td>' + QR4[24] + '</td><td>' + QR4[25] + '</td></tr>');
</script>
</table>
As I suspect you want to combine the QR[24] and QR[25] elements in one row, that's what I did in my second code sample. But if that's the situation, your array structure isn't very logical.
I gave you the code samples to select data from Javascript arrays and put them in HTML tables, now it's on you to use it the way you need it.. Because that isn't clear to me at all..
Assuming you already have the table defined, you can use some simple DOM methods to add and delete rows.
var table = document.getElementById("mytable");
for(i=0; i < QR4.length;i++) {
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
cell.innerHTML = QR4[i];
}

Categories