I have an HTML page with a search function that returns a table of search results. For each row of the table, there is a drop-down for the amount to donate and a Donate button. I would like to post the value from the row upon clicking Donate, but am unable to figure it out.
I have the confirm alert working with all the correct row information on click, but I am unable to set the hidden input value from within that function. So I made a second function results() and tried to set the value from that, but it's not working. If I just set it with some text (document.getElementById('donation').value = "some_text"), that works fine. But I would like to set the data from the row in which the button was clicked and set it as a value for POST.
This is my code:
{% extends "layout.html" %}
{% block title %}
Donate
{% endblock %}
{% block main %}
<form action="/donate" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="name"
placeholder="What animal would you like to support?" type="text" size="40">
</div>
<button id="search" class="btn btn-primary" type="submit" name="search">Search</button>
</form>
<br>
<table class="table" id="sponsor_table">
<thead class="thead-light">
<tr>
<th scope="col">Scientific Name</th>
<th scope="col">English Name</th>
<th scope="col">Red List Category</th>
<th scope="col">Donation</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{% for animal in animals %}
<tr>
<th scope="row">{{ animal.canonicalName }}</th>
<td>{{ animal.vernacularName }}</td>
<td>{{ animal.redlistCategory }}</td>
<td> <select id="price" name="price" onChange="calc();">
<option value="">Amount</option>
<option value="25">$25.00</option>
<option value="50">$50.00</option>
<option value="100">$100.00</option>
<option value="200">$200.00</option>
<option value="500">$500.00</option>
<option value="1000">$1000.00</option>
</select>
</td>
<form action="/donate" method="post">
<td><input name="donation" type="hidden" value="">
<button id="donation" class="btn btn-primary" name="donation" value="Donate" >Donate</button></td>
</form>
</tr>
{% endfor %}
</table>
<script type="text/javascript">
$(document).ready(function () {
// code to read selected table row cell data (values).
$("#donation").on('click',function(){
// get the current row
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").text(); // get current row 1st TD value
var col2=currentRow.find("td:eq(1)").text(); // get current row 2nd TD
var col3=currentRow.find("td:eq(2) option:selected").text(); // get current row 3rd TD
var col4=currentRow.find("td:eq(3)").text(); // get current row 3rd TD
confirm("Would you like to support the " + col2 + " " + col1 + " population with a donation of " + col3 + "?");
});
});
function results()
{
var rowId = event.target.parentNode.parentNode.id;
var data = document.getElementById(rowId).querySelectorAll(".row-data");
var species = data[0].innerHTML;
var name = data[1].innerHTML;
var category = data[2].innerHTML;
var amount = data[3].innerHTML;
return species;
} ;
document.getElementById('donation').value = results();
</script>
{% endblock %}
SOLVED:
<form action="/donate" method="post">
<td><input name="donation" type="hidden" id="test" value="">
<button id="donation" class="btn btn-primary" name="donation" value="Donate" >Donate</button></td>
</form>
</tr>
{% endfor %}
</table>
<script type="text/javascript">
$(document).ready(function () {
// code to read selected table row cell data (values).
$("#donation").on('click',function(){
// get the current row
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").text(); // get current row 1st TD value
var col2=currentRow.find("td:eq(1)").text(); // get current row 2nd TD
var col3=currentRow.find("td:eq(2) option:selected").text(); // get current row 3rd TD
var col4=currentRow.find("td:eq(3)").text(); // get current row 3rd TD
confirm("Would you like to support the " + col2 + " " + col1 + " population with a donation of " + col3 + "?");
document.getElementById('test').value = [col1, col2, col3];
});
});
Related
Below is code for adding inputs into a dynamic table and for each row an edit button is also generated, my question is how would I pass the values in the table back into the input fields when I click on the edit button of a specific row and then update the specific row based on the changes made to the values in the input fields when i click on the update row button.
$("#btnAdd").on('click', function() {
let row = '<tr> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
$('tbody').append(row);
$('td:contains("edit")').html("<button type='button'>" + "edit" + "</button>").on('click', function() {
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">Add to Table</button>
<button type="button" id="btnUpdate">Update row</button>
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
Check this (Read JS comments)
$("#btnAdd").on('click', function() {
let row = '<tr> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
$('tbody').append(row);
$('td:contains("edit")').html("<button type='button' class='edit'>" + "edit" + "</button>").on('click', function() {
});
});
//--------------------------------------------------------//
$(document).on("click",".edit",function(){ // Click function on class '.edit' (your appended button)
var name = $(this).parents("tr").find("td:eq(0)").html(); // Search for 'name' depending on this edit button parent.
var surname = $(this).parents("tr").find("td:eq(1)").html(); // Search for 'surname' depending on this edit button parent.
var rowNumber = $(this).parents("tr").index() // Get index of this edit button parent 'row'.
$("#edit-name").val(name); // Read the name and put it in '#edit-name' inside '.editArea'.
$("#edit-surname").val(surname); // Read the surname and put it in '#edit-surname' inside '.editArea'.
$(".saveEdits").attr("for",rowNumber); // Store this row index as attribute in '.saveEdits' button to be able to pass it to the other function that saves data.
$(".editArea").fadeIn(300); // Show the edit box.
});
$(".saveEdits").click(function(){ // Function to save data
var rowNumber = parseInt($(this).attr("for")); // Get the row number that we already define in the prev. function.
$('td:eq(0)','tr:eq('+(rowNumber+1)+')').html($("#edit-name").val()); // Update 'td' content depending on the 'tr' index.
$('td:eq(1)','tr:eq('+(rowNumber+1)+')').html($("#edit-surname").val()); // Update 'td' content depending on the 'tr' index.
});
$(".cancel").click(function(){ // Button to cancel edit.
$("#edit-name").val(""); // Empty value.
$("#edit-surname").val(""); // Empty value.
$(".saveEdits").attr("for","0"); // Set row number to zero.
$(".editArea").fadeOut(300); // Hide edit area.
});
.editArea{
display:none;
background:#fff;
padding:10px;
border:1px solid #ddd;
border-radius:5px;
box-shadow:0 0 0 #000;
width:50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">
Add to Table
</button>
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<div class='editArea'>
<label>Name</label>
<input type="text" id="edit-name">
<br>
<label>Surname</label>
<input type="text" id="edit-surname">
<hr>
<button class='saveEdits' for="0">Save edits</button>
<button class='cancel'>Cancel</button>
</div>
</body>
</html>
Here is a solution with edit row in just within existent inputs
var counter = 0;
var current_row = null;
$("#btnAdd").on('click', function() {
if (current_row == null) {
if ( $("#insert-surname").val().length && $("#insert-name").val().length ) {
let row = '<tr data-row="'+counter+'"> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
$('tbody').append(row);
counter++;
}
} else {
var select_row = $('tr[data-row='+current_row+']');
let cells = $(select_row).find('td');
$(cells[0]).text($("#insert-name").val());
$(cells[1]).text($("#insert-surname").val());
}
clear_input();
$('td:contains("edit")').html("<button type='button'>" + "edit" + "</button>").on('click', function() {
let cells = $(this).parents('tr').find('td');
$("#insert-name").val($(cells[0]).text());
$("#insert-surname").val($(cells[1]).text());
current_row = $(this).parents('tr').data('row');
});
});
$('#btnCancel').on("click", () => clear_input());
function clear_input() {
current_row = null;
$("#insert-name").val('');
$("#insert-surname").val('');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">Add to Table</button>
<button type="button" id="btnCancel">Cancel</button>
<table id='data-table'>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
Now let's begin with what wrong with the OP's solution. OP is trying to add event listner to an element which hasn't been created yet. The way we listen to dynamic data is through event delegation.
So for this:
<tbody>
// dynamic <tr></tr>
</tbody>
We would attach our listener to some parent of it (not necessarily the closest parent) i.e., <tbody> in this case which is part of the dom when we run our js code.
I'm sure that there are various ways of doing it, but I gave it a shot by sticking close to your actual solution. Check it out:
function addToTable() {
// insertion into row
let name = $("#insert-name").val();
let surname = $("#insert-surname").val();
let row = `<tr>
<td>${name}</td>
<td>${surname}</td>
<td><button>Edit</button></td>
</tr>`;
$('#tbody').append(row);
// clearing input fields
$("#insert-name").val("");
$("#insert-surname").val("");
}
function editTable() {
let name = $("#insert-name").val();
let surname = $("#insert-surname").val();
// looking for tr with "active" class
let row = $("#tbody tr.active");
let rowArr = row[0].children;
rowArr[0].innerHTML = name;
rowArr[1].innerHTML = surname;
row[0].classList.remove("active");
// clearing input fields
$("#insert-name").val("");
$("#insert-surname").val("");
}
$("#btnAdd").on('click', function() {
let isEdit = $("#btnAdd").hasClass("edit");
if (isEdit) {
editTable();
} else {
addToTable();
}
// remove class "edit"
$("tbody").removeClass("edit");
});
// Adding event listner to the parent (event delegation)
$("#tbody").on('click', function(e) {
$("#btnAdd").addClass("edit");
// pass table data to input fields
let row = e.target.closest("tr");
row.classList.add("active");
let rowArr = row.children;
$("#insert-name").val(rowArr[0].innerHTML);
$("#insert-surname").val(rowArr[1].innerHTML);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form>
<div>
<label for="insert-name">Name:</label>
<input type="text" id="insert-name">
</div>
<div>
<label for="insert-surname">Surname:</label>
<input type="text" id="insert-surname">
</div>
</form>
<button type="button" id="btnAdd">
Add to Table
</button>
<table>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
I am trying to get the data from all rows and save it to database. how to get data from table.
Thanks for any help.
This is my javascript file
$(document).ready(function(){
$("input").click(function(){
$(this).next().show();
$(this).next().hide();
});
});
function add_row(){
var order_table = document.getElementById('order_list');
var food_name = document.getElementById('food0')
var food_quantity = document.getElementById('quantity')
// Insert new row
var new_row = order_table.insertRow(0);
var nee_cell0 = new_row.insertCell(0);
var nee_cell1 = new_row.insertCell(1);
var nee_cell2 = new_row.insertCell(2);
var nee_cell3 = new_row.insertCell(3);
var nee_cell4 = new_row.insertCell(4);
nee_cell0.innerHTML = "{{ forloop.counter }}";
nee_cell1.innerHTML = food_name.value;
nee_cell2.innerHTML = food_quantity.value;
nee_cell3.innerHTML = 'safakat';
nee_cell4.innerHTML = 'safakat';
}
This is my Html file.
<body>
<input list="food_item" name="food0" id="food0" placeholder="Search for food item"><br>
<input type="number" name="unit_price">
<input type="number" name="quantity" id="quantity" placeholder="Enter The Quantity"><br>
<button onclick="add_row()">ADD ROW</button>
<table align="center" name = 'table'>
<tr>
<th>Sl. No.</th>
<th>Item</th>
<th name='abc'>Quantity</th>
<th>Unit Price</th>
<th>Amount</th>
</tr>
</table>
<table align="center" id="order_list">
</table>
<datalist id="food_item">
{% for i in food %}
<option value="{{i.name}}">
{% endfor %}
</datalist>
</body>
I am trying request.POST.getlist('table_name'). but i am getting empty list
I have a grid with some items and I´d like to sum val_itemservico column from selected rows. My template sums all rows.
I´d like to sum val_itemservico column only for selected rows when I click on "Calcular" button. In this case, I need to know if ind_selecionado column is checked.
So, how can I do that?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ORÇAMENTO</title>
</head>
<h2>ORÇAMENTO</h2>
<form class=" bd-form-20 " action="#" name="form-name" method="GET">
{% csrf_token %}
<label>Serviço: </label>{{filter.form.servico}}
<button type = "submit" >OK</button>
<br><br>
</form>
<tbody>
<div class=" bd-customhtml-29 bd-tagstyles bd-custom-table">
<div class="bd-container-inner bd-content-element">
<table id="table" border="1" rules="all" cellspacing="0" cellpadding="10"> <!--width="100%" border="0" cellspacing="0" cellpadding="2">-->
<tr>
<th>Selecionar</th>
<th>ID Item Serviço</th>
<th>Item Serviço</th>
<th>Valor Serviço</th>
<th>Serviço</th>
</tr>
{% for item in response.object_list %}
<tr>
<td> <input type="checkbox" id="item.ind_selecionado"></td>
<td>{{ item.id }}</td>
<td>{{ item.desc_itemservico }}</td>
<td>{{ item.val_itemservico }}</td>
<td>{{ item.servico_id}}</td>
</tr>
{% endfor %}
{% if response.object_list %}
Total: {{ response.object_list|length }}
{% endif %}
<br><br>
</table>
<br><br>
Valores:<br>
{% for item in response.object_list %}
{{item.val_itemservico}}<br>
{% endfor %}
<br><br>
<span id="sumV"></span>
<script>
var table = document.getElementById("table");
getSum();
function getSum()
{
var sumVal = 0;
for (var i = 1; i < table.rows.length; i++){
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
console.log("Sum: " + sumVal)
}
</script>
<br><br>
<button onclick="getSum();">Calcular</button>
</div>
</div>
</tbody>
</html>
You have to test for the value of the check input inside your loop that calculate the sum
for (var i = 1; i < table.rows.length; i++){
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
should be replaced by something like :
for (var i = 1; i < table.rows.length; i++){
if(table.rows[i].cells[1].childNodes[0].checked){
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
}
I'm having hard time with js and jquery executing events, I guess there is something I'm missing in my understanding of jquery.
Because I'm really new to this language, I'm confused and need some orientation if you can help me please.
what I need:
I have a form as a row, and a button that adds a new form everytime I click on it. also the new generated forms have different Ids and names.
Now every form contains two selects and need a change function to be excuted on it.
Where should I write this change function, so that every row have his own change function without getting confused with other rows.
EDIT :
<div id="myDIV1" style="display: inline">
<form action="/banque" method="POST" enctype="multipart/form-data" id="personForm" data-tiers-url="{% url 'ajax_load_tiers' %}" >{% csrf_token %}{{ form.non_field_errors }}
<table style ="border-collapse: separate;border-spacing: 15px;" id="id_forms_table">
<tr><td width="5%">N P</td><td width="8%">Date d'operation</td><td width="25%">Désignation</td><td width="10%">Type tiers</td><td width="10%">Tiers</td><td width="10%">Référence de Facture</td><td width="10%">Montant debit </td><td width="10%">Montant crédit</td></tr>
{% for form in formset %}
<tr style="border:1px solid black;" id="{{ form.prefix }}-row" class="dynamic-form" >
<td{% if forloop.first %} class="" {% endif %}><div class="col-xs-1"><b><p name="np1">1</p></b></div></td>
<td>
{% render_field form.dateOperation class="form-control" %}{{form.dateOperation1.errors}}
</td>
<td>{% render_field form.designation class="form-control" %}{{form..errors}}
</td>
<td>
{% render_field form.typeTiers class="form-control" %}{{form.typeTiers.errors}}
</td>
<td>
{% render_field form.tiers class="form-control" %}{{form.tiers.errors}}
</td>
<td>{% render_field form.numfacture class="form-control" %}{{form.numfacture.errors}}
</td>
<td>{% render_field form.montantdeb class="form-control" %}{{form.montantdeb.errors}}</td>
<td>{% render_field form.montantcred class="form-control" %}</td>
</tr>
{% endfor %}
<tr>
</tr>
</table>
{{ formset.management_form }}
<tr>
<!-- BUTTONS <td colspan="4">add property</td> -->
<td width="16%"><input type="submit" name="annuler" value="Annuler" class="btn btn-danger" style="float:right ;margin: 5px; margin-right: 35px"></td>
<td width="16%"><button value="" class="btn btn-success" style="float:right;margin: 5px;" onclick="verifier()">enregistrer</button></td>
</form>
<td><input type="submit" name="ajoutligne" value="Ajouter une ligne" class="btn btn-primary" id="add-row" style="background-color: #8C1944; border-color: #8C1944; float:right;margin: 5px;" onclick="test()"></td></tr>
</div>
On change of each added row by the button Ajouter une ligne , I need to execute the following change function:
$("#id_form-"+0+"-typeTiers").change(function () {
alert($('#id_form-'+0+'-typeTiers').attr('name'));
var url = $("#personForm").attr("data-tiers-url");
var typeID = $(this).val();
$.ajax({
url: url,
data: {
'tiers': typeID,
},
success: function(data) { // `data` is the return of the `load_cities` view function
alert(data);
var i=1;
var listeClt = $(data).clone(true).find('option[id=facvente],option[id=fadepenses],option[id=frs]').remove().end().html();
var listefactVentes= $(data).clone(true).find('option[id=clt],option[id=fadepenses],option[id=frs]').remove().end().html();
var listefrs = $(data).clone(true).find('option[id=facvente],option[id=fadepenses],option[id=clt],option[id=cnss]').remove().end().html();
var listefactDep= $(data).clone(true).find('option[id=clt],option[id=facvente],option[id=frs]').remove().end().html();
// var cnss= $(data).clone(true).find('select').remove().end().html();
if(listeClt!=0){
$("#id_form-"+0+"-tiers").html(listeClt);
$("#id_form-"+0+"-numfacture").html(listefactVentes);
}
else if(listefrs!=0){
$("#id_form-"+0+"-tiers").html(listefrs);
$("#id_form-"+0+"-numfacture").html(listefactDep);
}
else {
$("#id_form-"+0+"-tiers").html(data);
}
}
});
});
"#id_form-"+0+"-typeTiers" is the id of the first row select , "#id_form-"+0+"-tiers" is the Id of the select that will get populated after changing "#id_form-"+0+"-typeTiers" of the same row.
this jquery changes the first row correctly, but what about rows tha will be add after ? their fields will have as Ids 1 , 2 .. etc instead of 0 .
Any help would be great. Thank You in advance
Please look on this some samples. it may helps you
https://www.aspsnippets.com/Articles/Add-Insert-Remove-Delete-Table-Rows-dynamically-using-jQuery.aspx
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-append-and-remove-table-row-dynamically
function addData() {
var rows = "";
var ID = document.getElementById("id").value;
var Task = document.getElementById("task").value;
rows += "<tr><td>" + ID + "</td><td>" + Task + "</td></tr>";
var tbody = document.querySelector("#table tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
<body>
<form onsubmit="" method="POST">
ID:
<input type="text" id="id" required>New task:
<br>
<textarea id="task" required></textarea>
<br>
<input type="submit" value="Add" onclick="addData()">
</form>
<h3>Task Table</h3>
<div id="excell">
<table id="table" cellspacing="0px" cellpadding="25px" text-align="center">
<thead>
<tr>
<td>ID</td>
<td>Task</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
I'm learning Javascript and I'm trying to implement a small "ID and Task" table, but somehow it only works when I enter only 1 type of data such as only ID or only task, when I enter 2 data at the same time, nothing happens. I'd be grateful if you tell me what is the problem and how can I fix it. Thank you.
Here's my HTML
<body>
<form onsubmit="" method="POST">
ID:
<input type="text" id="id" required>
New task:<br>
<textarea id="task" required></textarea>
<br>
<input type="submit" value="Add" onclick="addData()">
</form>
<h3>Task Table</h3>
<div id = "excell">
<table id = "table" cellspacing = "0px" cellpadding = "25px" text-align = "center">
<thead>
<tr>
<td>ID</td>
<td>Task</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
and here's my JS
function addData() {
var rows = "";
var ID = document.getElementById("id").value;
var Task = document.getElementById("task").value;
rows += "<tr><td>" + ID + "</td><td>" + Task + "</td></tr>";
var tbody = document.querySelector("#table tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
Actual problem with your code is, you have used Submit button. Normally when a submit button is hit it post the data to action property of the form tag, which means transfer the page to next; if action property is not given, it give flickering effect and stay with current page and made all components with empty. The same is happen in your code also.
Better Change the code
<input type="Submit" value="Add" onClick="addData();"/>
into
<input type="BUTTON" value="Add" onClick="addData();"/>
and try its worked fine.