Javascript: Parsing html table - javascript

I am working on a html page. The page has a table with 3 columns and a button. One of the columns of the table is a check box (The number of rows are changed dynamically):
<table cellpadding="0" cellspacing="0" border="1" class="display" id="tag" width="100%">
<tbody>
<tr>
<td align="center">
<input type="checkbox" class="case" name="case" value="0"/>
<td>fruit</td>
<td>apple</td>
</tr>
<tr>
<td align="center">
<input type="checkbox" class="case" name="case" value="1"/>
<td>fruit</td>
<td>pear</td>
</tr>
</tbody>
</table>
<p><input type="button" value="Generate" onclick="generate()"></p>
When user click the "Generate" button, the generate() function will generate a special string base on the column of each row.
My question is that how can I check if the "checkbox" row is checked or not? I would like to filter those non-checked rows when I generate the string.
Thanks.

Filter the rows based upon which have a checked checkbox:
var rows = $(".case:checked").closest("tr");
This returns a jQuery object that contains all of your table rows housing checked checkboxes.

Call getElementsByName will give you an array of references of your checkboxes.
Loop the array in order to get the values.
var arr = document.getElementsByName("case");
for(i = 0; i < arr.length; i++){
if(arr[i].checked){
doSomething;
}
}

Related

how to change form values on selecting required values using laravel 5 and js

I am facing a problem couples of hours has been passed but i am not able to find my solution.
what i want is i have a from where i am adding a property in my form there two radio buttons 1- Vacational 2- Longterm .
If i select vacational and submit my form my form values submitted after submitting the values are shown on front end and there is button Rates when i click on this button the popup appears:
It shows 1- Season 2- Dates 3- Daily 4- Weekly 5- Monthly ( in case if i select radion button vacational) what i want here if i select radio button longterm the form should display value 1- Season 2- Dates 3- Monthly not daily and weekly but i am unable to show my required values:
My HTML where radio options is:
<label class="radio-inline">
<input type="radio" id="inlineCheckbox1" value="is_vacation" name="property_type" checked> Vacation
</label>
<label class="radio-inline">
<input type="radio" id="inlineCheckbox2" value="is_long_term" name="property_type"> Long Term
</label>
and i am doing like this of js code:
function longterm() {
alert("1");
document.getElementById('daily').style.display ='none';
document.getElementById('weekly').style.display ='none';
}
and my form where i am giving ids:
<thead>
<tr>
<th>Season</th>
<th>Dates</th>
<th id="daily" style="width: 150px; ">Daily</th>
<th id="weekly" style="width: 150px; ">Weekly</th>
<th id="monthly" style="width: 150px; ">Monthly</th>
</tr>
</thead>
I want to display only 3 options 1 - Season 2- Dates 3- Monthly how i can do that your help will be really appreciated! Need your help!
Here is an example of the suggestion I had in the comment of your original post. It could certainly be trimmed down and optimized however I wanted to illustrate what is actually happening.
window.removeColumns = function removeColumns(idsToRemove) {
// get the table to remove the columns from
var table = document.querySelector('#tbl');
// get all the headers in that table
var headers = table.querySelectorAll('thead td');
var removeIndex = [];
// loop over all the headers
for (var i = 0; i < headers.length; i++) {
// loop over the id array passed in
for (var removeCheck = 0; removeCheck < idsToRemove.length; removeCheck++)
// check if the headers id matches any of the ids passed in
if (headers[i].id == idsToRemove[removeCheck]) {
// remove the header
headers[i].parentNode.removeChild(headers[i])
// mark the column index for removal later
removeIndex.push(i);
}
}
// get all the rows
var rows = document.querySelectorAll('#tbl tbody tr');
// loop over the rows
for (var r = 0; r < rows.length; r++) {
// get all the cells
var cells = rows[r].querySelectorAll('td');
// loop over the remove indexes
for (var c = 0; c < removeIndex.length; c++)
// remove the cell from the row
rows[r].removeChild(cells[removeIndex[c]]);
}
}
<table id="tbl">
<thead>
<th>
<tr>
<td id="testRemoval">Remove</td>
<td>Test</td>
<td>Test</td>
</tr>
</th>
</thead>
<tbody>
<tr>
<td>Remove</td>
<td>Test</td>
<td>Test</td>
</tr>
<tr>
<td>Remove</td>
<td>Test</td>
<td>Test</td>
</tr>
</tbody>
</table>
<input type="button" onclick="window.removeColumns(['testRemoval']);" value="remove column" />
If this solves your problem please don't forget to mark it as the accepted answer.

How to add an id to an array by clicking on checkbox with javascript?

I have a table with some values, the last input is a checkbox.
I need to save the id of the input into an array only when is checked.
This is my partial table:
<table id="produtcTable" class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Producto</th>
<th scope="col">Precio de lista</th>
<th scope="col">Agregar</th>
</tr>
</thead>
<tbody>
<tr th:each="stock : ${stockList}">
<td th:text="${stock.productName}"></td>
<td th:text="${stock.price}"></td>
<td class="text-center">
<input class="form-check-input" type="checkbox" th:attr="id=${stock.stockCode}" onclick="myFunction(this)" aria-label="...">
this is my javascript that does not work:
<script >
function myFunction(product) {
var arr= [];
$('input[id='+ product.id +']:checked').each(function () {
arr.push(product.id);
});
alert(arr.toString());
};
</script>
what am I doing wrong?
I can't see a id attribute on you checkbox in you snippets. But there is some code i can not identify (not mentioned in post) setting the id. Please make sure there is an id in your current DOM (Browser Development tools: inspector). According to your snippet you can try the follwing:
<input type="checkbox" id="cb1" onclick="myFunction(this)"/>
<input type="checkbox" id="cb2" onclick="myFunction(this)"/>
and the following JS code would update an global array the the clicked checkbox id:
var arr= [];
function myFunction(inputCB) {
arr.push(inputCB.id);
alert(arr);
}

Get the selected rows from a table

I have a table that has 10 rows and 3 columns and each row has a checkbox associated with it. The user can select any number of rows and when he presses the Submit button an alert message needs to be displayed containing the values in all the selected rows preferably as a JSON string. How do I extract all the selected rows alone and convert it to a JSON string using either Javascript or Jquery?
I hope I've understood your requirements well. Please consider this solution.
$('#btn-table-rows').click(function (event) {
var values = [];
$('table #row-selector:checked').each(function () {
var rowValue = $(this).closest('tr').find('td.row-value').text();
values.push(rowValue)
});
var json = JSON.stringify(values);
alert(json);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<td>
<input id="row-selector" type="checkbox"/>
</td>
<td class="row-value">Row #1: Hello</td>
</tr>
<tr>
<td>
<input id="row-selector" type="checkbox"/>
</td>
<td class="row-value">Row #2: World</td>
</tr>
</table>
<button id="btn-table-rows">Process</button>

Last Clicked Radio button ID

I have table which consists of multiple rows and each row consists of Radio button in the first column as follows:
<table class="table table-condensed span8" id="AllocationTable">
<thead>
<tr>
<th title="Entity to Allocate" style="width: 30%">Entity</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.EntityAllocations)
{
<tr>
<td>
<input type="radio" name="radio" id="#item.ID" class="EntityRadioSelect" value="#item.ID" onclick="EntitySelect(this)" disabled="disabled" >
</td>
</tr>
}
</tbody>
</table>
Now I want to capture the Ids of the last clicked radio button
I have tried something like this
function EntitySelect(select) {
if ($(select).parent().data("lastClicked")){
alert($(select).parent().data("lastClicked"));
}
$(select).parent().data("lastClicked", select.id);
}
But I am getting the wrong value as it is giving me current value and sometime other values which is not accepted answer.
var clicked='';
var preClicked='';
$("#AllocationTable").on("click",".EntityRadioSelect",function(){
preClicked=clicked;
clicked=$(this).attr("id");
});
remove onclick="EntitySelect(this)"
try this:
function EntitySelect(select) {
var parent=$(select).parents('#AllocationTable');
if (parent.data("lastClicked")){
alert(parent.data("lastClicked"));
}
parent.data("lastClicked", select.id);
}

how to change value of one input text field (in one html table) based on a specific value of another input text field (present in another html table)

I have one html table which has one row. This row has two TDs which hold their own tables within them (Each having 10 rows with 10 input fields). I want to change value of another respective text field based on value change in first field onblur().
First field-. It takes value from an Array of size 10
<tr>
<td valign="top">
<table width="85%" border="0" cellpadding="2" cellspacing="1" class="inputTable">
<tr>
<td width="60%">
<table width="60%" border="0" cellpadding="0" cellspacing="1">
<c:set var="input1" value="${someForm.value1}"></c:set>
<c:forTokens items="0,1,2,3,4,5,6,7,8,9" delims="," var="count">
<tr>
<td><input id="field1" name="field1" type="text" value="<c:out value="${input1[count]}" />" onblur="setText2(this)" maxlength="20" size="15">
</td>
</tr>
</c:forTokens>
</table>
</td>
</tr>
</table>
</td>
Second field. This requires value chnage on run when respective value changes for above 10 fields
<td valign="top">
<table width="85%" border="0" cellpadding="2" cellspacing="1" class="inputTable">
<tr>
<td width="60%">
<table width="60%" border="0" cellpadding="0" cellspacing="1">
<c:forTokens items="0,1,2,3,4,5,6,7,8,9" delims="," var="count">
<tr>
<td><input id="field2" name="field2" type="text" value="" />" readonly class="readonly" maxlength="1" size="1">
</td>
</tr>
</c:forTokens>
</table>
</td>
</tr>
</table>
</td>
</tr>
Javascript:
<script>
function setText2(element) {
if(element.value)
{
document.getElementById("field2").value = element.value;
}else{
document.getElementById("indicator").value = "";
}
}
</script>
This is running fine. But problem is I am able to identified which field is being changed through this but unable to get reference of target field. This changes value of second fields but always in first row of second table.
Please help me to run this so that if a field changes of table1 , then the repective (same serial) field of table 2 should change. I cant change the table structure due to some project limitations.
getElementById() is selecting the first element with id="field2". You shouldn't give the same id to multiple elements. Try changing the id to correspond to the count, then in your javascript function you can get the field2 input that corresponds to the count of the blurred input.
Replace your field1 code with this:
<input id="field1_${count}" name="field1" type="text" value="${input1[count]}"
onblur="setText2(this)" maxlength="20" size="15"/>
Replace your field2 code with this:
<input id="field2_${count}" name="field2" type="text" value=""
readonly="readonly" class="readonly" maxlength="1" size="1">
Then change your javascript function:
function setText2(element) {
if(element.value)
{
var changedId = element.id;
var elementNumber = changedId.substring(changedId.indexOf('_') + 1);
document.getElementById("field2_" + elementNumber).value = element.value;
}else{
document.getElementById("indicator").value = "";
}
}
As answered by Tap, assign distinct id for each field (of array). The only thing I want to add is, we should use c:out while assigning number to id as given below (otherwise id will not have numbers as being expected rather it will assign string as "field1_${count}" ):
Use:
<input id="<c:out value="field1_${count}" />" name="field1" type="text" value="<c:out value="${input1[count]}" />" onblur="setText2(this)" maxlength="20" size="15"/>
This runs well!! ;)
I am happy; this solved my big problem without affecting structure of the code...
Thanks a lot again Tap, for your suggestion. :)

Categories

Resources