Get An Element Within a Table Row - javascript

Firstly,
If possible, I would like to do this without JQuery, and purely Javascript.
Ok so I have an html table with rows getting added dynamically to it.
In each row is a:
Select Element (id = "ddFields")
Text Input Element (id = "tfValue")
Button Element (no id)
The Button Element removes the row for which it is situated
The Select Element has a default option of "" and then other 'valid' options
The Text Input is added to the row but it is hidden.
All elements are in the same
Basically I would like for the Select Element to show the hidden text input element if the selected index is != 0
so far I have this for my onchange function:
function itemChanged(dropdown) //called from itemChanged(this)
{
var cell = dropdown.parentNode;
var row = cell.parentNode;
var rowIndex = dropdown.parentNode.parentNode.rowIndex;
var index = dropdown.selectedIndex;
var option = dropdown.options[dropdown.selectedIndex].text;
if(index >0)
{
alert(row);
var obj=row.getElementById("tfValue"); //tfValue is the Text Field element
alert(obj);
//row.getElementById("tfValue").hidden = "false"; //doesn't work
//row.getElementById("tfValue").setAttribute("hidden","true"); //doesn't work
}
else
{
alert('none selected');
}
}

Finally figured it out. So here it is:
SCENARIO:
A table that has rows added to it dynamically.
In each row there is a select element and an input text element.
The select element changes text-value of the input text element based on the index of the select element.
in your select element set the onchange function to this:
onchange="selectionChanged(this)"
then create a javascript function shown below:
function selectionChanged(dropdown)
{
//get the currently selected index of the dropdown
var index = dropdown.selectedIndex;
//get the cell in which your dropdown is
var cell = dropdown.parentNode;located
//get the row of that cell
var row = cell.parentNode;
//get the array of all cells in that row
var cells = row.getElementsByTagName("td");
//my text-field is in the second cell
//get the first input element in the second cell
var textfield = cells[1].getElementsByTagName("input")[0];
//i use the first option of the dropdown as a default option with no value
if(index > 0)
{
textfield.value = "anything-you-want";
}
else
{
textfield.value = null;
}
}
Hope this helps whoever. It bugged me for a very long time. Thanks shub for the help! :)

first, I hope you are not repeating your ids. No two items should have the same id.
If you're iterating, create id1, id2, id3.
Also, this is not necessary but I suggest introducing your vars like this:
var a = x,
b = y,
c = z;
If you decide to use jQuery you could just do this:
$('#tableid').on('click','button',function(){
$(this).parent().parent().remove();
});
$('#tableid').on('change', 'select',function(){
if($(this).val()){ $(this).next().show(); }
});
Be sure to change #tableid to match your table's id.
This assumes the text input is the very next element after the select box. If not so, adjust as necessary or ask and I'll edit.

Related

SearchingThrough Table that uses input tags

I am trying to search through a table, which works alright without input tags, however I want to keep the input tags inside the table cells. I have tried using td.firstElementChild.value but this did not work.... what do I need to fix in order to search through the table?
here is my fiddle: https://jsfiddle.net/Souleste/1fxxzoe7/114/
One solution is to include a common className to be us used by all input elements.
You already do this when creating the input controls:
input1.className = 'input';
Though, I recommend maybe using a more descriptive className, but either will work as long as the className is unique to the input controls on the page:
input1.className = 'search-input';
You also already have a unique id for each TR (row) element.
tr.id = 'row' + rowCount;
Add this id as a data- attribute on the input element, like so:
input1.setAttribute('data-tr-id', 'row' + rowCount);
Now, get the inputs by className and inspect the values:
var inputElements = document.getElementsByClassName('search-input');
inputElements.foreach(function(item, index){
var value = item.value;
// use the data-tr-id attribute to find the TR element to hide/show
var trElementId = item.getAttribute('data-tr-id');
var trElement = document.getElementById(trElementId);
// do the value comparison and hide/show as needed
if (value.toUpperCase().indexOf(filter) > -1) {
tr.style.display = '';
} else {
tr.style.display = 'none';
}
});

find element by id in innerhtml

I have an asp.net gridview with one column as a template filed with a panel with some controls like textbox and dropdown list.
So, onclick, with js I can give the value of a cell by row and column, but in this panel column how can I get the inner elements?
function t3(tab, element, NParents, col)
{
//alert("t3")
var grd = document.getElementById(tab);
if (grd != null)
{
var row = element
for (i = 0; i < NParents; i++)
{
row = row.parentNode
}
alert(grd.rows[row.rowIndex].cells[col].innerHTML)
}
}
innerHtml give me the HTML of the panel, now how can I find its elements?
but in this panel column how can i get the inner elements?
You can use querySelector to query the DOM element
var cell = grd.rows[row.rowIndex].cells[col];
var textbox = cell.querySelector( "input[type='text']" ); //will return input box inside the text
var select = cell.querySelector( "select" ); //will return dropdown inside the text

Form values are overwritten after change

I have a form that shows up when each row in a table is double clicked. The values of this form can be updated and the form should be submitted with all row changes. But each time I double click on a row and edit the values of that form for that row, the previous values I had changed get overwritten. In order to work around this, I tried adding all the changes to a map with the row id as the key and the values of the form as the value. But the form still won't update with the new values. Here is a fiddle to demonstrate what I mean:
https://jsfiddle.net/4fr3edk7/2/
If I double click on the row that says "Adam Smith" and change that name to John Doe, when I double click on the second row and then double Click on "Adam Smith" again, it should say "John" on the first textbox and "Doe" on the second one. But the new value never seems to save.
This code snippet loops through each key, then loops through each value of that key:
for(var i = 0; i<key.length; i++){
var getval = globalchanges[key[i]];
for(var k=0; k<getval.length; k++){
$("#input1").val(getval[0]);
$("#input2").val(getval[1]);
}
}
How can I get the new changes to save? (The table rows don't have to show the changes, just the textbox values). Any help would be appreciated.
First, as mentioned by #Taplar you are binding the click event multiple times. Your approach is close enough, the idea of storing the changes is valid. You should have 2 functions, store the changes on button click and the second one to retrieve the changes by id.
Updated Fiddle
This function will get the values of the form and will store in on a global object
function setMap(id){
var firstrow = $("#input1").val();
var secondrow = $("#input2").val();
globalchanges[id] = [firstrow,secondrow];
}
This other function will check if the global object has values for the passed id, if not, it will use the values on the row
function getMap(id, tr){
if(globalchanges[id] != undefined && globalchanges[id].length == 2){
$("#input1").val(globalchanges[id][0]);
$("#input2").val(globalchanges[id][1]);
}
else{
$("#input1").val($(tr).find('td').eq(1).text());
$("#input2").val($(tr).find('td').eq(2).text());
}
}
Please note there are also changes on the dbclick and click events, they should be separated
$("#table tr").dblclick(function(){
$("#txtbox-wrapper").css({"display" : "block"});
var id = $(this).find('td').eq(0).text();
$('#id').val(id);
getMap(id,this);
});
$("#savebtn").click(function(){
var id = $('#id').val();
setMap(id);
});
And that we added and additional input to store the id on the form.
You are going to need to rethink your logic because of this part
$("#table tr").dblclick(function(){
$("#txtbox-wrapper").css({"display" : "block"});
var id = $(this).find('td').eq(0).text();
$("#input1").val($(this).find('td').eq(1).text());
$("#input2").val($(this).find('td').eq(2).text());
$("#savebtn").click(function(){
addToMap(id);
});
});
-Every time- you double click a table row you are adding a new click binding to the savebtn element. This means if you double click both rows, when you click that button it will execute addToMap for both ids. You may have other issues with your logic relying on only two other inputs for multiple rows, but this double/triple/+ binding is going to bite you.
There are few changes required in your logic as well as implementation.
1: Do not bind save event inside row click.
2: You are selecting the value in row double click event from td element. You need to update this element to keep your logic working
3: Keep track of which row is getting updated.
Updated Code
var globalchanges = {};
var rowSelected = null;
$("#table tr").dblclick(function() {
$("#txtbox-wrapper").css({
"display": "block"
});
rowSelected = $(this).find('td').eq(0).text();
$("#input1").val($(this).find('td').eq(1).text());
$("#input2").val($(this).find('td').eq(2).text());
});
$("#savebtn").click(function() {
addToMap(rowSelected);
});
function addToMap(row) {
var array = [];
var changes = {};
var firstrow = $("#input1").val();
var secondrow = $("#input2").val();
array.push(firstrow, secondrow);
globalchanges[row] = array;
makeChanges(row);
}
function makeChanges(row) {
var key = Object.keys(globalchanges);
console.log(key);
$("#table tr td").each(function(k, v) {
if ($(v).text() == key) {
$(v).next().html(globalchanges[row][0]);
$(v).next().next().html(globalchanges[row][1]);
globalchanges = {};
}
});
}
Working fiddle : https://jsfiddle.net/yudLxsgu/

jquery array of nodes

I have a table with 2 columns. One column with a checkbox and another one with plain text. I would like to generate an object array with the the check state and the text. I can go tr after tr with this:
$('#divInfCambios .frozen-bdiv tr').each(function(i)
{ ... }
How can access to td[1], check the state, and recover the text of td[2]?
I got the check state with:
$(this).find('input[type="checkbox"]').prop('checked')
I need now how to access node 2 (td[1]) and grab the text.
//run through each row
$('#divInfCambios .frozen-bdiv tr').each(function (i, row) {
var getInputByName = $(this).find('input[name="selection"]');
if (getInputByName.is(':checked') ){
}
// assuming you layout of the elements
var tds = $(this).find('td');
var getTdText = tds.eq(1).text();
});

How the select the multiple Table data as per selected checkbox?

There is one data table with two rows, as per below image
When user click on 2bit it should highlight that TD in that column only. I achieved this using jQuery for one check box selection, but when multiple check box selection like 2 and 4 it should highlight both the TD.
http://jsbin.com/exazoh/edit#preview working example for single value highlight.
Code: http://jsbin.com/exazoh/2/edit
Try the following function:
jQuery(function() {
// on change of an input with a name starting with "bit-select"...
jQuery('input[name^="bit-select"]').change(function(){
var checked = this.checked,
val = this.value,
column = $(this).closest("th").index() + 1;
// for each td in the current column
jQuery("#tableData tr.data td:nth-child(" +
column + ")").each(function() {
var $td = $(this);
// does the current td match the checkbox?
if ($td.text() == val) {
if (checked)
$td.addClass("jquery-colorBG-highLight");
else
$td.removeClass("jquery-colorBG-highLight");
}
});
});
});
I had to add the value attributes to the second set of checkboxes.
Working demo: http://jsbin.com/exazoh/4/edit#preview
Or the short version, since I notice you were using .filter() originally:
jQuery(function() {
jQuery('input[name^="bit-select"]').change(function(){
var method = this.checked ? "addClass" : "removeClass",
val = this.value;
jQuery("#tableData tr.data td:nth-child("+($(this).closest("th").index()+1)+")")
.filter(function(){return $(this).text()==val;})[method]("jquery-colorBG-highLight");
});
});
Demo: http://jsbin.com/exazoh/5/edit

Categories

Resources