How to sum only selected rows from a list - javascript

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

Related

Set input value for post from results of javascript function

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];
});
});

i want to count the number of correct answers in jS or jquery

I want to count the number of correct answers and display it.i tried many ways but couldn't go through.will appreciate if anybody can help me .Thanks in advance.
{% extends 'base.html' %}
{% block title%}Quiz{% endblock title %}
{% block content %}
<div class=" text-danger mt-5 text-center">
<!-- <h2><b id="count">Timer</b></h2> -->
<h3>+++Quiz on Indian Politics+++</h3>
<hr>
</div>
<div class="pt-5">
{% for item in obj %}
<table>
<tr>
<h2>Q{{item.id}}. {{item.question}}</h2><br>
</tr>
<tr>
<input type="radio" class="rd" name="{{item.id}}" id="opt1" value="{{item.opt1}}"> {{item.opt1}}</input><br>
</tr>
<tr>
<input type="radio" class="rd" name="{{item.id}}" id="opt2" value="{{item.op2}}"> {{item.opt2}}</input><br>
</tr>
<tr>
<input type="radio" class="rd" name="{{item.id}}" id="opt3" value="{{item.opt3}}"> {{item.opt3}}</input><br>
</tr>
<tr>
<input type="radio" class="rd" name="{{item.id}}" id="opt4" value="{{item.opt4}}"> {{item.opt4}}</input><br>
</tr>
<tr>
<label id="lb" class="rd" name="{{item.id}}" value="{{item.cor_ans}}" style='display:none;color:green'><b>The correct answer is: {{item.cor_ans}}</b></label>
</tr>
<tr>
</tr>
</table>
<hr> {% endfor %}
<div class="pt-4">
<button type="submit" class="btn btn-success" id="btn">Submit</button>
</div>
<div class="pt-3">
<b id="counter"></b>
<b id="ans"></b>
</div>
</div>
{% endblock content %}
{% block scripts %}
<script>
const rad = document.getElementsByClassName('rd')
const input = document.getElementsByTagName('input')
const bt = document.getElementById('btn')
const label = document.getElementsByTagName('label')
const counter = document.getElementById('counter')
var score = 0;
bt.onclick = function() {}
// JQuery code
$(document).ready(function() {
$('#btn').click(function() {
$('.rd').show();
$('.rd').attr("disabled", true);
});
});
// # javascript code
bt.addEventListener('click', function() {
for (i = 0; i < input.length; i++) {
if (input[i].type === 'radio') {
if (input[i].checked) {
document.getElementById('ans').innerHTML += "Q" + input[i].name + " The Answer you selected is: " + input[i].value + "<br>";
}
}
}
})
// var interval = setInterval(function(){
// document.getElementById('count').innerHTML=count;
// count--;
// if (count === 0){
// clearInterval(interval);
// document.getElementById('count').innerHTML='Done';
// alert("You're out of time!");
// }
// }, 1000);
// document.getElementsByClassName('counter').innerHTML = cnt;
// console.log(label[j].innerHTML.replace("<b>The correct answer is: ","").replace("</b>",""))
//
// if(label[j].innerHTML.replace("<b>The correct answer is: ","").replace("</b>","") == input[i].value){
// console.log("Hello")
// }
</script>
{% endblock scripts %}

Get data from table and save to database

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

Getting existing HTML in TR Body to Clear

I have a Jquery/Ajax call which updates cart details. At the moment I can't get the existing HTML in the cart-body(tablebody) to clear. The actual ajax request works and all items are added to cart but the original HTML entries stay. The particular code is here:
if (data.products.length > 0 ) {
productRows.html("")
$(cartBody).empty()
Jquery Function
function refreshCart() {
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
var productRows = cartBody.find(".cart-product")
var cartTotal = cartTable.find(".cart-total-sec")
var productQuantity = cartTable.find(".cart-item-quanity")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data) {
console.log("success")
console.log(data)
if (data.products.length > 0 ) {
productRows.html("")
$(cartBody).empty()
$.each(data.products, function(index, value) {
console.log(value)
console.log(data.count)
cartBody.append("<tr><td>" + value.quantity + " x" + "</td><td>"+ value.name + "</td><td>" + "£" + value.price + "</td></tr>")
})
cartTotal.find(".cart-total").text(data.total)
console.log(data.total)
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
HTML Form:
<div>
<h4>This is your shopping cart</h4>
<table class="cart-table">
<tr>These are the items in your basket and their respective totals</tr><br>
<tbody class="cart-body">
{% for item in cart.items %}
<form method="POST" action='{% url "shopping-cart-remove" %}'>
{% csrf_token %}
<tr class="cart-product"><span class="cart-item-quanity">{{ item.quantity }}</span> x {{ item.product.name }} = {{ item.subtotal }}</tr>
<input type="hidden" name='id' value='{{ item.product.id }}'>
<span class='remove-span'><button>remove</button><br></span>
</form>
</tbody>
{% endfor %}
<tr class="cart-total-sec"><td class="cart-price">{{ cart.total }}</td></tr>
</div>
Any help is really appreciated.
First you are making mistake, as i can see there's form in table, on refreshing you will lose that form so i guess you should append items in form not in .cart-body.
And for emptying html use cartBody.html(""); and you don't have to use productRows.html("") at all.
The issue as pointed out by Ultrazz008, was that the HTML was incorrectly formatted. For reference:
<table class="cart-table">
<tbody class="cart-body">
<form method="POST" class='form-product-ajax' action='{% url "shopping-cart-remove" %}' data-endpoint='{% url "shopping-cart-remove" %}'>
{% csrf_token %} {% for item in cart.items %}
<tr class=cart-product>
<td>{{ item.quantity}} x {{ item.product.name }} {{ item.subtotal }}
<input type="hidden" name='id' value='{{ item.product.id }}'>
<button class='remove-btn'>remove</button>
</td>
{% endfor %}
</tr>
</form>
</tbody>
<tr class="cart-total-sec">
<td class="cart-price">{{ cart.total }}</td>
</tr>
</table>

SyntaxError: Unexpected token ILLEGAL on Function Call

I know what this error is generally from but I just can't find it in my code. I know it is the statement:
button.setAttribute("onclick", "makeUneditable(" + row_id + ")")
And I've included all the code so you can know what you're looking at. And just fyi {{row}} is a list that I pass in with Jinja2 and then convert to a string in javascript. But I am not sure what in that statement is illegal. Any ideas?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function makeEditable(row_id) {
row_id = String(row_id)
var row = document.getElementById(row_id);
row.setAttribute("contenteditable", "true")
var button = document.getElementById(row_id+"_button");
button.setAttribute("onclick", "makeUneditable(" + row_id + ")")
button.innerHTML = "Done Editing";
}
function makeUneditable(row_id) {
row_id = String(row_id)
console.log(row_id)
var row = document.getElementById(row_id);
row.setAttribute("contenteditable", "false")
}
</script>
</head>
<body>
<table class="TFtable" style="width:300px">
<thead>
{% for column_name in column_names %}
<th>{{column_name}}</th>
{% endfor %}
</thead>
{% for row in table %}
<script>
document.writeln('<tr id="' + String({{row}}) + '">');
</script>
{% for cell in row %}
<td>{{cell}}</td>
{% endfor %}
<td contenteditable="false">
<script>
document.writeln('<button id="' + String({{row}})+'_button"');
</script>
type="button" onclick="makeEditable({{row}})">Edit Connector</button>
</td>
</tr>
{% endfor %}
</table>
</body>
Use single quotes around your value when concatenating it:
button.setAttribute("onclick", "makeUneditable('" + row_id + "')")

Categories