Bootstrap striped table format lost when updating table with fetch - javascript

I am using Django and I have a table which is formatted using bootstrap. The class is class="table table-striped". The table initially looks good. It has a delete button which allows users to delete a row. When clicked the data is deleted from the Django model and the table rows are removed and repopulated using fetch. Everything works well but the striped formatting is lost. The bootstrap formatting is still working to some degree and the table is the same size/shape but the background colour of alternating striped rows is lost. I've tried removing and re-adding the class with the javascript but it doesn't work. Any suggestions would be great.
HTML
{% if pairs %}
<table class="table table-striped" id="pairs_table">
<thead>
<tr>
<th scope="col">Primer</th>
<th scope="col">Product(bp)</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{% for pair in pairs %}
<tr>
{% if pair.forward.pk == primer.pk %}
<td>
{{ pair.reverse }}
</td>
<td>{{ pair.product }}</td>
<td id="delete_pairing">
<button type="button" class="btn btn-warning" onclick="delete_pair('{{primer.id}}','{{pair.reverse.id}}')"><i class="bi bi-trash3"></i></button>
</td>
{% else %}
<td>
{{ pair.forward }}
</td>
<td>{{ pair.product }}</td>
<td id="delete_pairing">
<button type="button" class="btn btn-warning" onclick="delete_pair('{{primer.id}}','{{pair.forward.id}}')"><i class="bi bi-trash3"></i></button>
</td>
{% endif %}
</tr>
{% endfor %}
JAVASCRIPT
table_div = document.getElementById('table_div')
table = document.getElementById('pairs_table');
// If no pairs after deleting, removing table and replacing with text
if(json.length == 0){
table.remove();
table_div.innerHTML = "Currently no available pairs";
table_div.append(document.createElement("br"),document.createElement("br"));
}
else{
// delete all rows except headings
while (table.rows.length > 1) {
table.deleteRow(1);
}
for(x in json){
pair_name = json[x].pair;
pair_id = json[x].pair_id;
product = json[x].product;
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.href = `/primer/${pair_id}`;
cell1.innerHTML = `<a href=/primer/${pair_id}>`+pair_name+'</a>';
var cell2 = row.insertCell(1);
cell2.innerHTML = product;
var cell3 = row.insertCell(2);
cell3.id = "delete_pairing";
cell3.innerHTML = `<button type="button" class="btn btn-warning" onclick="delete_pair('${primer_id}','${pair_id}')"><i class="bi bi-trash3"></i></button>`;
}
}
}```

Related

hide table heading if all values in table are null

I have a model form that I am displaying in a table. The form has about 40 fields broken down into 6 different tables. I have setup an if statements to not display the table elements if the field is empty in the db. This works as expected the only issue is that if all the elements are hidden the table header is still displayed. How could I hide the table header if all if the elements in that particular table are hidden.
<table class="post-table">
<tr>
<th class="table-header" colspan="2">
<h3>Pool Details</h3>
</th>
</tr>
<tbody>
{% if post.pool_size != '' %}
<tr>
<td>pool size:</td>
<td>{{ post.pool_size }}</td>
</tr>
{% endif %}
{% if post.pool_style != '' %}
<tr>
<td>Pool Style:</td>
<td>{{ post.pool_style }}</td>
</tr>
{% endif %}
</tbody>
</table>
Update:
<table class="post-table">
<tr>
<th class="table-header" COLSPAN="1" id="tab_header">
<H3>ADDITIONAL INFO</H3>
</th>
</tr>
<tbody id="tab_body">
{% if post.additional_info != '' %}
<tr>
<td>{{ post.additional_info }}</td>
</tr>
{% endif %}
</tbody>
</table>
<br>
<script>
let tbody = document.getElementById("tab_body").innerHTML;
if (tbody === '') {
tab_header = document.getElementById("tab_header").innerHTML = " ";
} else {
// Nothing to do i guess
}
</script>
You can use JavaScript to hide the header if the <tbody> is empty :
Suppose that we have <th id="tab_header">Tab header</th> <tbody id="tab_body">Some content here</tbody>
Then
let tbody = document.getElementById("tab_body").innerHTML;
# Check if it contains something
if (tbody === '') {
tab_header = document.getElementById("tab_header").innerHTML = "";
} else {
// Nothing to do i guess
}
NB Be aware about checking the content of may be it is not empty string but sme other thing else.
<table class="post-table" id="table-example">
<tr>
<th class="table-header" COLSPAN="1" id="tab_header">
<H3>ADDITIONAL INFO</H3>
</th>
</tr>
<tbody id="tab_body">
{% if post.additional_info != '' %}
<tr>
<td id="test">{{ post.additional_info }}</td>
</tr>
{% endif %}
</tbody>
</table>
<script>
var tbl = document.getElementById('table-example');
if (tbl.rows.length == 1) {
console.log('IT WORKED')
tab_header = document.getElementById("tab_header").innerHTML = "";
}
console.log(tbl.rows.length)
</script>

How to delete django dynamic formset with java script - issue with index?

In my template i'm using a formset to add a "Raum"-form dynamic.
In each row of my table, there is a button "delete row", so that i can delete the row again.
the java script code is as far as i can say is working quite well...
Adding and saving the forms works fine.
Also deleting with the java script code works fine.
Even when i delete the last row of the table, saving the forms works fine.
But when f.e. i add 3 rows (rooms), row1-row2 and row3, and i delete row 1 or row 2, i can not save my forms, because i think in view.py the is_valid method = false...
maybe i have to update some kind of index of my forms??? and how ??
any help is really apprecheated...
html template for adding rooms with the table and forms:
<table id="tableHeadToModify" class="table table-bordered">
<thead class="hg-rot schrift-weiss">
<tr>
<th colspan="2">Räume</th>
</tr>
{% for raum in raum_formset %}
{% if forloop.first %}
<tr>
<th>{{ raum.name.label_tag }}</th>
<th>{{ raum.name.label_tag }}</th>
</tr>
{% endif %}
{% endfor %}
</thead>
<tbody id="tableToModify">
{{raum_formset.management_form}}
{% for raum in raum_formset %}
<tr id="rowToClone">
<td> {{ raum.name }} </td>
<td><button type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
{% endfor %}
</tbody>
</table>
<button id="add-form" type="button" class="btn btn-outline-danger btn-md">add room</button>
<script>
let container = document.querySelector("#form-container")
let addButton = document.querySelector("#add-form")
let totalForms = document.querySelector("#id_form-TOTAL_FORMS")
let rowCount = document.getElementById('tableToModify').rows.length-1;
addButton.addEventListener('click', addForm)
function addForm(e){
e.preventDefault()
let formRegex = RegExp(`form-(\\d){1}-`,'g')
rowCount = document.getElementById('tableToModify').rows.length-1;
var row = document.getElementById("rowToClone"); // find row to copy
var table = document.getElementById("tableToModify"); // find table to append to
var clone = row.cloneNode(true); // copy children too
table.appendChild(clone); // add new row to end of table
rowCount++
clone.innerHTML = clone.innerHTML.replace(formRegex, `form-${rowCount}-`)
totalForms.setAttribute('value', `${rowCount+1}`)
}
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
var total = parseInt($('#id_form-TOTAL_FORMS').val());
if (total > 1) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("tableHeadToModify").deleteRow(i);
totalForms.setAttribute('value', `${rowCount}`)
}
}
}
views.py
formset_raum = RaumFormSet(data=self.request.POST)
#wenn die Eingabe der Formen passt
if kunde_form.is_valid() and angebot_form.is_valid() \
and objekt_form.is_valid() \
and formset_raum.is_valid():<--- this isn't valid

How to change the value of a data-attribute and a td in a table HTML e Jquery

I have this table in html, and I load it with Php Laravel
<div class="form-row col-md-12">
<table id="contacts" class="table table-striped">
<tbody>
<tr>
<th>Id</th>
<th>Cel</th>
<th>Tel</th>
<th>Email</th>
<th>Actions</th>
</tr>
#if(isset($contacts) && count($contacts)>0)
#foreach($contacts $c)
<tr>
<td class="inf" data-id="{{ $c->id }}"> {{ $c->id }} </td>
<td class="inf" data-cel="{{ $c->cel}}"> {{ $c->cel}} </td>
<td class="inf" data-tel="{{ $c->tel}}"> {{ $c->tel}}</td>
<td class="inf" data-email="{{ $c->email }}"> {{ $c->email }} </td>
<td>
<button class='btn btn-primary btnAlterarContato' type="button">Alterar</button>
</td>
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
You can see that each row has its data attribute for creating data. I made a method that I can retrieve the data from the TD and alter them, however I can not change the data of the data. how do I change how information that is without data attribute?
$('.btnAlterarContato').click(function(){
var Row= $(this).closest('tr');
var Posicao = 1;
// Switch: 1 = Id, 2 = Cel, 3 = Tel, 4 = Email
Row.find('td').each(function(){
switch(Posicao)
{
case 2: $(this).text('new value '); $(this).attr('data-cel', 'Hi');
$(this).data('data-cel','Hi') ;break;
}
Posicao++;
});
});
I have a repeat loop to walk on every table td, and in case position 2 is the value of cel, I would like to change your display item and your cell-date when I do $ (this) .text ('new value ') this works, but I can not change the mobile date, how do I do this?
For changing data attribute use .data() like below:-
$(this).data('cel', 'Hi');
Note:- Once clear your browser cache and check

jQuery + Django : get data from HTML table

I am struggling to obtain the text within a table using jQuery.
I have a HTML page set up as followed.
{% for element in list %}
<button class="btn btn-primary add" id="{{forloop.counter}}">Add</button>
<table class="table" id="myTable">
<thead>
<tr><td><h3>General information for {{ element.id }}</h3></td></tr>
</thead>
<tbody>
<tr><td><label id='name-{{forloop.counter}}' class="label label-success" >{{ element.Name }}</label></td></tr>
<tr><td><label id='address-{{forloop.counter}}' class="label label-success" >{{ element.Address }}</label></td></tr>
<tr><td><label id='code-{{forloop.counter}}' class="label label-success" >{{ element.Code }}</label></td></tr>
</tbody>
</table>
{% endfor %}
<script>
$(".add").click(function(e) {
var id = $(this).attr('id');
var test = $("myTable tr td").each(function() {
var name = $(this).find('#name-'+id).text();
var address = $(this).find('#address-'+id).text();
var code = $(this).find('#code-'+id).text();
alert(name);
alert(address);
alert(code);
});
});
</script>
For every object in the list, there is a button and a table. his table contains several rows holding the list data. I wish to retrieve the text in the <tr> tags and submit them later using ajax.
What am I doing wrong?
You need to change this line
$("myTable tr td")
to
$("#myTable tbody tr td") //missing pound sign & your tds are inside tbody

display a dialog window for each element of table when clicking on a button in twig view

I have this code in my twig view for my symfony project:
<table>
<thead>
<tr>
<th>DATA 1</th>
<th>DATA 2</th>
<th>DATA 3</th>
<th>DATA 4</th>
<th>DATA 5</th>
<th>DATA 6</th>
<th></th>
</tr>
</thead>
<tbody>
{% for currentData in arrayData %}
<tr>
<td>{{ currentData.data1}}</td>
<td>{{ currentData.data2}}</td>
<td>{{ currentData.data3}}</td>
<td>{{ currentData.data4}}</td>
<td>{{ currentData.data5}}</td>
<td>{{ currentData.data6}}</td>
<td>
<a><button class="btn btn-info btn-xs" id="show">Show Details</button></a> <!-- for open dialog window -->
<button class="btn btn-warning btn-xs">Edit</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<!-- dialog window-->
<dialog id="window">
<div class="header">
<ul class="nav nav-tabs">
<li role="presentation" class="active">
<a>Detail</a>
</li>
<button class="btn btn-danger btn-sm pull-right" id="exit">Close</button>
</ul>
</div>
<div class="panel-body page-header">
<!-- my content here -->
</div>
</dialog>
<script>
(function() {
var dialog = document.getElementById('window');
document.getElementById('show').onclick = function() {
dialog.show();
};
document.getElementById('exit').onclick = function() {
dialog.close();
};
})();
</script>
As you can see, it's a basic html page. I display all my datas in a table in my loop {% for currentData in arrayData %}.
On this table, there are two types of button: Show Details button and Edit button. The Edit button works well, there's no problem, my redirection works for all datas in my table and I can edit data I chose.
For the button Show Details: the desired behavior is that a window dialog opens in my page and contains every datas I need to display for each lines. But in fact, my dialog window works just on the first line of my table when clicking on Show Details, and when I click on another Show Details button of another line, nothing happened (really nothing).
Where am I wrong?
Note that for now, I don't pass datas in my window dialog, I make it through Ajax and Symfony Controller.
Because id is used to get a single dom element, and you shouldn't use same id on multiple dom elements, what you should do is add a class like show :
<a><button class="btn btn-info btn-xs show" id="show">Show Details</button></a>, then use document.getElementsByClassName('show') to get all the button that has the class show, then you can addEventlistener to each of them:
(function() {
var dialog = document.getElementById('window');
// Array of the buttons.
var showButtons = document.getElementsByClassName('show');
// Event handler
var showDialog = function() {
// Now you have to use the show button as base , to find the data you want
// to display...
console.log(this);
dialog.show();
};
var i, len = showButtons.length;
for(i = 0; i < len; ++i) {
showButtons[i].onclick = showDialog;
}
document.getElementById('exit').onclick = function() {
dialog.close();
};
})();
jsFiddle
You are using this line in the body of a loop:
<button class="btn btn-info btn-xs" id="show">
This will result in the id attribute not being unique – which is not valid and which will not work. You could append {{ loop.index }} to the current id value to generate unique IDs, or (better) use jQuery and do something like ...
$('button.btn.btn-info.btn-xs').on(
'click',
function() {
var clickedButton = $(this);
// do something ...
}
)
It's because you're trying to set the same id to all of your buttons. Don't do that - it's not valid HTML. You should use a class instead and grab ALL of your buttons with getElementsByClassName, like this:
var buttons = document.getElementsByClassName("show");
for(var i = 0; i < buttons.length; i++){
buttons[i].onclick = function(){
alert("Why hello there!");
};
}
Here's an example fiddle https://jsfiddle.net/0qaht3ry/

Categories