jQuery + Django : get data from HTML table - javascript

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

Related

Bootstrap striped table format lost when updating table with fetch

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>`;
}
}
}```

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

sending data from template to flask

I'm making a website using flask.
It displays a list using sql in top.html in which each element is a hypertext.
<table class="table table-striped">
<thead></thead>
<tr>
<th>Company</th>
</tr></thead>
<tbody>
{% for company in companies %}
<tr>
<td>{{ company.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
So i want to know which hypertext is clicked from the list so that i could load its respective content in /text.
please provide the python code also(flask code).
First put company unique identifier to each <a for example <a data-id="11" ...
Then add event listeners on each <a like this...
var companyLinks = document.querySelectorAll('.table-striped a');
for (var i = 0; i < companyLinks.length; i += 1) {
companyLinks[i].addEventListener('click', function (e) {
// get the company id of clicked link
var companyId = e.target.dataset.id;
// now do what you like with the company id
// for example you can send an AJAX call to your backend
});
}

html table edit the rows dynamically

I have an html table and i want to edit the contents of the table based on a button click.
My HTML code:
<form name="myform">
<table id="tblFollow" >
{% for key, value in result.iteritems() %}
<tr>
<td > {{ key }}</td>
<td> <div id="editableText" > {{ value }} </div></td>
</tr>
{% endfor %}
</tbody>
</table>
<h> {{ passvalue }} </h> <br>
<input type="button" onclick="changeContent()" value="Change content">
</form>
and my javascript is
function changeContent(){
var newstate = !editableText.isContentEditable
editableText.contentEditable = newstate
editableText.className = (newstate)
}
but the problem is when i click on the button only the first rown on the table is showing editable. otherthan that all the rows are immutable. Any help will be appreciated
You should use the class instead of id. Id's are meant to be unique.
<div class="editableText" > {{ value }} </div>
Then in your javascript, you need to loop over the selected elements:
function changeContent(){
var editables = document.getElementsByClassName('editableText');
for (var i = 0; i < editables.length; i++) {
var newstate = !editables[i].isContentEditable;
editables[i].contentEditable = newstate;
}
}

Categories