I have 20 rows in an HTML table, 3 radios in each row. I want randomly to select 1 of the 3 radios in every row.
I have a code snippet, but it does not work properly, because it checks more than 1 radios, or none.
Here is my javascript snippet:
function selectRandomRadioButton(radioButtons) {
const index = Math.floor(Math.random() * radioButtons.length);
const element = radioButtons[index];
element.checked = true;
return `Selected Option ${element.value}`;
}
var table = document.getElementById("randomtable");
var totalRowCount = table.rows.length;
for (let i = 1; i < totalRowCount; i++) {
document.addEventListener("DOMContentLoaded", () => {
const radioButtons = document.getElementsByClassName("random");
const message = selectRandomRadioButton(radioButtons);
console.log(message);
});
}
And here is my html:
<table id="randomtable">
<tr>
<th>#</th>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<tr>
<td>1</td>
<td><input type="radio" class="random" /></td>
<td><input type="radio" class="random" /></td>
<td><input type="radio" class="random" /></td>
</tr>
<tr>
<td>2</td>
<td><input type="radio" class="random" /></td>
<td><input type="radio" class="random" /></td>
<td><input type="radio" class="random" /></td>
</tr>
</table>
The table has 21 rows including the first, but I only pasted here 2 for example.
Related
How can I create an array of objects from an HTML table body? This is how my HTML looks like
<tbody id="metadata">
<tr>
<td><input type="numeric" /></td>
<td><input type="numeric" /></td>
</tr>
<tr>
<td><input type="numeric" /></td>
<td><input type="numeric" /></td>
</tr>
<tr>
<td><input type="numeric" /></td>
<td><input type="numeric" /></td>
</tr>
</tbody>
here is what I tried this javascript to get all the values from the table cell in an array of objects. I don't understand why my cMetadata always return a blank array
let cMetadata;
if (document.querySelectorAll("metadata")) {
let tableData = document.querySelectorAll("metadata");
cMetadata = [...tableData].map((row) => {
return {
altions: row.cells[0].textContent,
lexity: row.cells[1].textContent,
};
});
}
final array of object should look like
cMetadata = [{altions: 1 , lexity: 2},{altions: 2 , lexity: 2},{altions: 3 , lexity: 2}]
Verified that you have the tbody node inside a table node. You can get the items with document.querySelectorAll("#metadata tr"):
const btn = document.querySelector("button");
btn.addEventListener("click", () => {
const elements = document.querySelectorAll("#metadata tr");
const result = Array.from(elements).map(tr => {
const childs = tr.querySelectorAll("input");
return {
p1: childs[0].value,
p2: childs[1].value
};
});
console.log(result);
});
<table>
<tbody id="metadata">
<tr>
<td><input type="numeric"></td>
<td><input type="numeric"></td>
</tr>
<tr>
<td><input type="numeric"></td>
<td><input type="numeric"></td>
</tr>
<tr>
<td><input type="numeric"></td>
<td><input type="numeric"></td>
</tr>
</tbody>
</table>
<button>Get Data</button>
<!DOCTYPE html>
<html>
<body>
<!--External table-->
<table border="1px">
<tr>
<td>
//price and quantity fields
<input type="text" name="price" label="Price" id="Pri">
<input type="text" name="quantity" label="Quantity" id="Qty">
</td>
<td>
<!--internal table-->
<table border="1px">
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td><input type="checkbox" id="checx"/></td>
</tr>
<tr>
<td>11</td>
<td>22</td>
<td><input type="checkbox" id="checx"/></td>
</tr>
<tr>
<td>111</td>
<td>222</td>
<td><input type="checkbox" id="checx"/></td>
</tr>
<tr>
<td>10</td>
<td>20</td>
<td><input type="checkbox" /></td>
</tr>
</table>
</td>
</tr>
</table>
//Javascript
<script type="text/javascript">
checkboxes = document.getElementById("checx").getElementsByTagName("input");
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var secondColumn = currentRow.getElementsByTagName("td")[1];
var FirstColumn = currentRow.getElementsByTagName("td")[0];
alert("My text is: " + secondColumn.textContent +" "+ FirstColumn.textContent);
};
}
document.getElementById("Pri").value=secondColumn.textContent;
document.getElementById("Qty").value=FirstColumn.textContent;
</script>
//I have a dynamic table on the above pattern.I want in such a way that when I click on the checkbox on the internal table it should copy the values and should show on the input boxes on the corresponding row on the external table.
</body>
</html>
I have a dynamic table on the above pattern.I want in such a way that when I click on the checkbox on the internal table it should copy the values and should show on the input boxes on the corresponding row on the external table.
Thanks for your help in advance
the main issue that checkboxes ids has to be unique per element so you have to depend on class name rather than ids of checkboxes
in addition to the following code
document.getElementById("Pri").value=secondColumn.textContent;
document.getElementById("Qty").value=FirstColumn.textContent;
Has to be inside the event handler
<!DOCTYPE html>
<html>
<body>
<!--External table-->
<table id="parentTable" border="1px">
<tr>
<td>
//price and quantity fields
<input type="text" name="price" label="Price" id="Pri">
<input type="text" name="quantity" label="Quantity" id="Qty">
</td>
<td>
<!--internal table-->
<table border="1px">
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td><input type="checkbox" id="checx1" class="checx"/></td>
</tr>
<tr>
<td>11</td>
<td>22</td>
<td><input type="checkbox" id="checx2" class="checx"/></td>
</tr>
<tr>
<td>111</td>
<td>222</td>
<td><input type="checkbox" id="checx3" class="checx"/></td>
</tr>
<tr>
<td>10</td>
<td>20</td>
<td><input type="checkbox" id="checx4" class="checx" /></td>
</tr>
</table>
</td>
</tr>
</table>
//Javascript
<script type="text/javascript">
checkboxes = document.getElementsByClassName("checx");
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var secondColumn = currentRow.getElementsByTagName("td")[1];
var FirstColumn = currentRow.getElementsByTagName("td")[0];
alert("My text is: " + secondColumn.textContent +" "+FirstColumn.textContent);
document.getElementById("Pri").value=secondColumn.textContent;
document.getElementById("Qty").value=FirstColumn.textContent;
};
}
</script>
</body>
</html>
I want to sum all the text box value in a html table row using jQuery.
here is the table:
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
<th>HA</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input id="expenses_sum"></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input id="expenses_sum"></td>
</tr>
<tr>
<td>3</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input id="expenses_sum"></td>
</tr>
</table>
Here is the jQuery function to add the value of all text box of class expenses and display the result in a text box of id expenses_sum.
$(document).ready(function() {
$(".expenses").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
$(".expenses").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#expenses_sum").val(sum.toFixed(2));
}
how to use this function for each row.
Firstly you have repeated the same id when they should be unique which means your HTML is invalid. You should use a common class instead.
To make this work you need to restrict the .expenses selector to only find the elements within the same row as the input which was changed. To do that you can use closest() to get the nearest parent tr, then find() to get all the inputs.
Also note there are several logic improvements you can make here:
remove the each() loop to add the event handler
providing the reference of calculateSum to the event handler so you can use the this keyword to traverse the DOM
provide a default value of 0 to the value to simplify the sum logic
hook to the change event as well as keyup for when users paste data in to the field. Try this:
$(document).ready(function() {
$(".expenses").on('keyup change', calculateSum);
});
function calculateSum() {
var $input = $(this);
var $row = $input.closest('tr');
var sum = 0;
$row.find(".expenses").each(function() {
sum += parseFloat(this.value) || 0;
});
$row.find(".expenses_sum").val(sum.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
<th>HA</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses_sum"></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses_sum"></td>
</tr>
<tr>
<td>3</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses_sum"></td>
</tr>
</table>
you can use like this
$(document).on('keyup change','input.expenses',function(){
$expenses = $(this).parents('tr').find('.expenses');
$expenseTotal = $(this).parents('tr').find('#expenses_sum');
$expenseTotal.val('0');
$.each($expenses,function(index,object){
if($(object).val()!='')
{
$expenseTotal.val(parseInt($expenseTotal.val())+parseInt($(object).val()));
}
});
});
see demo at - https://jsfiddle.net/Vesharj/zLg3pyq4/
Here is the right way to do this.
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
<th>HA</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input class="expenses_sum"></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input class="expenses_sum"></td>
</tr>
<tr>
<td>3</td>
<td><input class="expenses"></td>
<td><input class="expenses"></td>
<td><input class="expenses"></td><td>
<input class="expenses_sum"></td>
</tr>
</table>
And js :
$(document).ready(function(){
$(".expenses").each(function() {
$(this).keyup(function(){
sum($(this).parents("tr"));
});
});
});
function sum(parent){
var sum = 0;
$(parent).find(".expenses").each(function(){
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$(parent).find(".expenses_sum").val(sum.toFixed(2));
}
Hope, it helps
I am new to Js. I have a table that shows me 9 persons. I have added the number of days they are in the group. I am trying to create a function that counts per day +1 to this number. Has somebody an Idea how i can do that?
This is my Code:
<table style="width:100%">
<tr>
<th><input class="checkbox" type="checkbox"></th>
<th>Spieler</th>
<th>Rang</th>
<th>Tage</th>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>HELLFIRE944</td>
<td>Komandant</td>
<td>212</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>Backfischjoghurt</td>
<td>Ausführender Offizier</td>
<td>217</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>retoaba</td>
<td>Personaloffizier</td>
<td>210</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>chrisi_39</td>
<td>Rekrutierungsoffizier</td>
<td>210</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>salpo</td>
<td>Unteroffizier</td>
<td>212</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>Kaeltischerkriger</td>
<td>Unteroffizier</td>
<td>213</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>DnerYoo_sniper</td>
<td>Rekrut</td>
<td>39</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>panzerzockerundnoah</td>
<td>Rekrut</td>
<td>146</td>
</tr>
<tr>
<td><input class="checkbox" type="checkbox"></td>
<td>PanzaSintKuhlMinecraftLP</td>
<td>Rekrut</td>
<td>116</td>
</tr>
</table>
<footer class=footer>
<div class=footer>
<p class= footer-p>created by #Reto Keller</p>
</div>
</footer>
This will help you, it returns you the whole array of tableData values of Tage.
plunker link
function getAllTableDataValues() {
var row = $('table tr'); //get all table rows
var rowData = row.find('td:nth-child(4n)'); // get all the table data with Tage
var numberArray = [];
rowData.each(function() {
var value = $(this).html(); //get the value of td in string format array
value = Number(value);
value = value +1;
numberArray.push(value);
});
return numberArray;
}
getAllTableDataValues();
I found javascript example on this site that hides rows based on reading a value directly within a cell within the row, but I need it to read the value within a text input field.
Here's the javascript I'm using:
function hide() {
var tbl = document.getElementById('Table'),
rows = tbl.tBodies[0].children, l = rows.length, i,
filter = function(cells) {
var values = [
parseInt(cells[0].firstChild.nodeValue.replace(/,/g,''),10),
parseFloat(cells[1].firstChild.nodeValue.replace(/,/g,''))
];
if( values[1] < 1) return false;
return true;
};
for( i=0; i<l; i++) {
if( !filter(rows[i].cells)) rows[i].style.display = "none";
}
}
Here's the HTML:
<tr>
<tdRow 1</td>
<td>1<input id="Quantity1" name="Quantity1" class="numericValue" type="text" value="1" /></td>
</tr>
<tr>
<td>Row 2</td>
<td>2<input id="Quantity2" name="Quantity2" class="numericValue" type="text" value="2" /></td>
</tr>
<tr>
<td>Row 3</td>
<td>3<input id="Quantity3" name="Quantity3" class="numericValue" type="text" value="0" /></td>
</tr>
<tr>
<td>Row 4</td>
<td>4<input id="Quantity4" name="Quantity4" class="numericValue" type="text" value="0" /></td>
</tr>
<tr>
<td>Row 5</td>
<td>0<input id="Quantity5" name="Quantity5" class="numericValue" type="text" value="0" /></td>
</tr>
<input id="btnSubmit" onclick="hide();" type="submit" value="Hide" /></p>
As is, the js will read the "0" in Row 5 and hide it, but I want Rows 3,4, and 5 with the input values of "0" to be hidden. How do I get at the input value? this is for a table in which the input values will all start at "0" (for a quantity), then one or more of the values will be changed.
Thanks.
Just need to change a single line:
parseFloat(cells[1].firstChild.nodeValue.replace(/,/g,''))
becomes
parseFloat(cells[1].firstElementChild.value.replace(/,/g,''))
Fiddle