Javascript getting total sum from wrong checkbox trigger - javascript

Below are two different checkbox and the javascript below seems to be trigger by termsChkbx checkbox instead of chosen. How do I change this portion
var chosen = item.parentElement.querySelector('[type="checkbox"]'); ?
echo "\t<div class='item'>
<span class='CDTitle'>{$CD['CDTitle']}</span>
<span class='CDYear'>{$CD['CDYear']}</span>
<span class='catDesc'>{$CD['catDesc']}</span>
<span class='CDPrice'>{$CD['CDPrice']}</span>
<span class='chosen'><input type='checkbox' id='selectChkbx' name='CD[]' value='{$CD['CDID']}' title='{$CD['CDPrice']}' /></span>
</div>\n";
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>
JS:
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>" + num + "<br/>";
}
document.getElementById("selectChkbx").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
total+=parseFloat(chk[i].value);
}
}
document.getElementById("total").innerHTML = total;
}
createCheckbox();

You can try something like this:
JSFiddle
Code
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>" + num + "<br/>";
}
document.getElementById("content").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
total+=parseFloat(chk[i].value);
}
}
document.getElementById("total").innerHTML = total.toFixed(2);
}
createCheckbox();
<div id="content"></div>
<p id="total">0</p>
Edit 1
I believe reason why you are not getting value is because of element structure. You have a span tag which holds price and another span tag holds checkbox. For such structure, you will have to navigate to that span and fetch its value. Following is depicted below.
Fetching Span's value
var price = chk[i].parentNode.previousSibling.textContent;
Code
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<span>" + num + "</span>";
html += "<span><input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>Check</span><br/>";
}
document.getElementById("content").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
var price = chk[i].parentNode.previousSibling.textContent;
total += parseFloat(price);
}
}
document.getElementById("total").innerHTML = total.toFixed(2);
}
createCheckbox();
.chk{
}
<div id="content"></div>
<p id="total">0</p>

Related

Having trouble calculating the value of a list of classes in Javascript

I'm trying to add all the values from the class "q-total" But I can't get it to work. Here's the code:
$(document).on("change", ".row-inputs", function(){
var total = 0;
var price = 0;
var multi = 0;
$('.q-quantity', this).each(function(){
multi = $(this).val();
})
$(".q-price", this).each(function(){
price += +$(this).val() * multi;
})
$(".q-total", this).val(price);
for (var i = 0; i < $(".q-total").length; i++) {
// total = 0;
// console.log($(".q-total", this).val() )
total += parseInt($(".q-total", this).val());
}
console.log("Total " + total)
})
Below is the class code I use to add new rows to the html. In case this might help to figure out why the above code is not working.
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + "
inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.className = "row-inputs";
newdiv.innerHTML = "<input type='text' name=''
placeholder='product name' class='q-product-name'> " +
"<input type='number' name='' placeholder='0' class='q-quantity'
value=1> " +
"<input type='text' name='' placeholder='price' class='q-price'> "
+
"<input type='text' name='' placeholder='price' class='q-total'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
Thank you
Your loop is incorrect:
Change
for (var i = 0; i < $(".q-total").length; i++) {
// total = 0;
// console.log($(".q-total", this).val() )
total += parseInt($(".q-total", this).val());
}
To
$(".q-total").each(function(){
total += +$(this).val();
})
In the original for loop you never iterate over the values, you always take $(this).val(). Not sure why you varied from your .each() approach you've used everywhere else, but that is your fix.
To explain further, using your example of add rows with prices of 3,4,5. The first time through (1st row), you have one element in the jQuery collection, so total=0 becomes total += 3; Second row added and you have two elements, but only look at the value of the current row, so total=0 becomes total += 4 && total += 4 hence total=8; On third row change, there are three elements, to total = 15 ( 3 * 5);

Not work JavaScript function delete

I have the following JavaScript where I get data from a DataBase for my shopping cart. But when I want to delete cart data it does not work my code.
I do not know if I'm getting well into this part of the code
javascript:deleteRow(this).
I leave the complete code of my two functions: listarPedido() and (at the bottom) deleteRow(r).
function listarPedido(){
var articulos = localStorage.getItem("productos");
var productos = articulos.split(";");
var contador = 0;//cuenta numero de articulos en el carrito
for( var i = 0; i < productos.length - 1; i++ ){
var item = productos[i].split(",");
var pedido = "";
for( var j = 0; j < item.length; j++ ){
pedido = '<tr>'+
'<td class="text-center">'+ '<img style="width: 100px; height: 100px" src="' + item[0] + '"/></td>' +
'<td id="celiminar" style="text-align:left;"><b>'+ item[1].toUpperCase() + '<br><br><br><br></b>' +
'<a style="text-decoration:none">Editar</a> | Delete</td>' +
'<td style="text-align:right; color:red"><b>'+ 'S/.'+ item[2] + '</b></td>' +
'<td class="text-center"><b>'
+ '<input type="number" name="txtcant'+i+'" id="txtcant'+i+'" min="1" max="15" value="'+ item[3] +'" class="form-control">' +
'</b></td>'+
'<td style="text-align:right;"><b>'+ 'S/.'+ (item[2]*item[3]).toFixed(2) + '</b></td>';
}
//<i class="fa fa-trash"></i>
$("#detallePedido").append(pedido);
$("#txtcant"+i).change(function(){
resumen();
//al cambiar el numero actualiza el total
$("#detallePedido tr").find("td").eq(4).html('<b>'+ 'S/.'+ (item[2] * $(this).val()).toFixed(2)+ '</b>');
});
contador++;
}
$("#lblnum").text(contador +" ARTÍCULOS");
}
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById(".table").deleteRow(i);
}
Your code is simply wrong:
document.getElementById(".table").deleteRow(i);
I doubt you have an element with the ID ".table".
Your function, rewritten to get the proper table:
function deleteRow(link) {
var row = link.parentNode.parentNode;
var idx = row.rowIndex;
var table = row.parentNode;
table.deleteRow(idx);
}

Create a new dropdown with javascript

I am trying to create a dropdown after I choose an option in an original dropdown.
This is the HTML code:
<br>
<select id ="select-container" onchange="addSelect('select-container');">
<option>test1</option>
<option>test2</option>
<option>test3</option>
</select>
<br>
This is the javascript.
function categorygenerate() {
//for testing purposes
var categoryarray = new Array(),
i;
for (i = 0; i < 3; i++) {
categoryarray[i] = Math.random();
}
return categoryarray;
}
function addSelect(divname) {
var newDiv = document.createElement('div');
var html = '<select>',
dates = categorygenerate(),
i;
for (i = 0; i < dates.length; i++) {
html += "<option value='" + dates[i] + "'>" + dates[i] + "</option>";
}
html += '</select>';
newDiv.innerHTML = html;
document.getElementById(divname).appendChild(newDiv);
console.log($("#" + divname).html());
console.log(newDiv);
}
The debugger mode shows me no error.
It is because you are trying to append your code in the "original select": look at the id of your select.
You have to add a div tag with the id="select-container" and remove it from the "original select"
Here is a working snippet:
function categorygenerate() {
//for testing purposes
var categoryarray = new Array(),
i;
for (i = 0; i < 3; i++) {
categoryarray[i] = Math.random();
}
return categoryarray;
}
function addSelect(divname) {
var newDiv = document.createElement('div');
var html = '<select>',
dates = categorygenerate(),
i;
for (i = 0; i < dates.length; i++) {
html += "<option value='" + dates[i] + "'>" + dates[i] + "</option>";
}
html += '</select>';
newDiv.innerHTML = html;
document.getElementById(divname).appendChild(newDiv);
console.log($("#" + divname).html());
console.log(newDiv);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>
<select onchange="addSelect('select-container');">
<option>test1</option>
<option>test2</option>
<option>test3</option>
</select>
<br>
<div id="select-container"></div>
Put your select in a div with the id select-container. Ofcourse, give your select an other ID. Then your code should work. It's because you try to append a new select to the original one in your HTML.
https://jsfiddle.net/b248a4k1/

Wrote javascript to dynamically create table. Need help validating user input

I already have a table being created in javascript. It is based off user input and will check to make sure the value entered is a number. But how do I ALSO make it check to make sure the values entered are
higher then 0
and less then 10
<html>
<head>
<title>Homework 1</title>
<script language="javascript" type="text/javascript">
function doWork(){
var rows = document.getElementById("input1").value;
var columns = document.getElementById("input2").value;
//alert(rows);
//alert(columns);
if(isNaN(rows) == true || isNaN(columns) == true){
document.getElementById('tablePlacement').innerHTML = "Input must be integer";
}
else{
var htmlInput = "";
htmlInput += "<table border='1'>";
htmlInput += "<tr>";
//Column Headers
for (i = 0; i <= columns; i++){
htmlInput += ("<td><b>" + i + "</b></td>");
}
htmlInput += "</tr>";
for (i = 1; i <= rows; i++){
htmlInput += ("</br><tr><td><b>" + i + "</b></td>");
for (j = 1; j<= columns; j++){
var multiplyResult = i * j;
htmlInput += ("<td>" + multiplyResult + "</td>");
}
htmlInput += "</tr>";
}
htmlInput += "</table>";
document.getElementById('tablePlacement').innerHTML = htmlInput;
}
};
</script>
</head>
<body>
<form id="input1Form">
Rows: <input type="text" id="input1">
</form>
<form id="input2Form">
Columns: <input type="text" id="input2">
</form>
<button type="button" onclick="doWork()">Enter</button>
<div id="tablePlacement">
</div>
</body>
if(rows <=0 || rows >= 10){
document.getElementById('tablePlacement').innerHTML = "Input rows must be between 1 and 9";
}
if(cols <=0 || cols >= 10){
document.getElementById('tablePlacement').innerHTML = "Input cols must be between 1 and 9";
}

Dynamically creating an html table with Javascript

I am trying to create a table based on user input (actually two or three tables depending on the user input..) using Javascript, I am very much native to PHP and have already got this working in PHP, however i would like the user to be able to see the table before the query it. I found a script on here that partially did what I wanted and have attempted to edit it (I found it surprisingly similar to PHP) Basically it calculates the total amount of cells (ports) splits it by rows and columns, the "super" column is used if the user would like it to be split into multiple tables, which align next to each other, hence the div tag. Here's my JS:
<html>
<head>
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for(u=1; u<=num_row; u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
</script>
</head>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
Here is what the final output looks like after it has been processed by PHP (ports:24, col:6, rows:2, super:2):
Here is a js fiddle that I threw together:
http://jsfiddle.net/9SnLB/
Currently, when I click the button nothing happens, but, I suppose that is my first issue, but am I going about the setup correctly? Why wont the button run the function?
Two mistakes. One you didn't close the function bracket, ie a missing } at the end. The second is you used $row instead of the variable you created num_rows. For some reason it doesn't work in the fiddle, it does however work locally. The fiddle is saying the createTable function is undefined.
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for($u=1; $u<=num_rows; $u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}
var table = [["a1","a2","a3"]["b1","b2","b3"]["c1","c2","c3"]];
for(x = table.length;x > 0;x--) {
document.write("<tr>");
for(y = table[x].length;y > 0;y--) {
document.write("<td>"+y+"</td>");
}
document.write("</tr>");
}
Sorry if the syntax is wrong. You get the idea.
You need to change your jsFiddle framework to "no wrap (head)" and correct errors in the javascript. "no wrap (head)" will allow access the function. The "for ($u=1" loop is missing the close brace and $row should be num_rows. The "for (j=0" loop is missing a semicolon at the last "tbody=".
here's the corrected js.
function createTable() {
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for (var i = 0; i < num_super; i++) {
var theader = '<div><table border="1">\n';
for ($u = 1; $u <= num_rows; $u++) {
tbody += '<tr>';
for (var j = 0; j < colStart; j++) {
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>';
}
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}

Categories