as explain on solution for the issue:
Using arrows-keys to navigate
http://jsfiddle.net/BdVB9/
I have same table with some text input, and I got some problem to select text in input box in tables cells during navigating between cells.
can any one help me to solve it? navigation works fine but not select text in input box!!! and also i want to navigate only between cells that have input-box, not all them
Notes: I just want to navigate between cells that have text input-box.
table codes:
<table border="1" id="navigate">
<tbody>
<tr>
<td><input type="text" id="1" class="input"></td>
<td></td>
<td><input type="text" id="3" class="input"></td>
<td></td>
<td><input type="text" id="5" class="input"></td>
</tr>
<tr>
<td><input type="text" id="6" class="input"></td>
<td><input type="text" id="7" class="input"></td>
<td></td>
<td><input type="text" id="9" class="input"></td>
<td><input type="text" id="10" class="input"></td>
</tr>
<tr>
<td><input type="text" id="11" class="input"></td>
<td><input type="text" id="12" class="input"></td>
<td></td>
<td><input type="text" id="14" class="input"></td>
<td><input type="text" id="15" class="input"></td>
</tr>
</tbody>
</table>
and this is my own demon
I put together a fiddle with the functionality you specified http://jsfiddle.net/tppiotrowski/L7cm8/10/. I hope I understood your requirements correctly. Let me know if you need any alterations or do not understand the code. Good luck!
var active = 0;
//$('#navigate td').each(function(idx){$(this).html(idx);});
rePosition();
$(document).keydown(function(e) {
reCalculate(e);
rePosition();
// if key is an arrow key, don't type the user
// input. if it is any other key (a, b, c, etc)
// edit the text
if (e.keyCode > 36 && e.keyCode < 41) {
return false;
}
});
$('td').click(function() {
active = $(this).closest('table').find('td').index(this);
rePosition();
});
function reCalculate(e) {
var rows = $('#navigate tr').length;
var columns = $('#navigate tr:eq(0) td').length;
var temp;
if (e.keyCode == 37) { //move left or wrap
temp = active;
while (temp > 0) {
temp = temp - 1;
// only advance if there is an input field in the td
if ($('#navigate tr td').eq(temp).find('input').length != 0) {
active = temp;
break;
}
}
}
if (e.keyCode == 38) { // move up
temp = active;
while (temp - columns >= 0) {
temp = temp - columns;
// only advance if there is an input field in the td
if ($('#navigate tr td').eq(temp).find('input').length != 0) {
active = temp;
break;
}
}
}
if (e.keyCode == 39) { // move right or wrap
temp = active;
while (temp < (columns * rows) - 1) {
temp = temp + 1;
// only advance if there is an input field in the td
if ($('#navigate tr td').eq(temp).find('input').length != 0) {
active = temp;
break;
}
}
}
if (e.keyCode == 40) { // move down
temp = active;
while (temp + columns <= (rows * columns) - 1) {
temp = temp + columns;
// only advance if there is an input field in the td
if ($('#navigate tr td').eq(temp).find('input').length != 0) {
active = temp;
break;
}
}
}
}
function rePosition() {
console.log(active);
$('.active').removeClass('active');
$('#navigate tr td').eq(active).addClass('active');
var input = $('#navigate tr td').eq(active).find('input').focus();
scrollInView();
}
function scrollInView() {
var target = $('#navigate tr td:eq(' + active + ')');
if (target.length) {
var top = target.offset().top;
$('html,body').stop().animate({
scrollTop: top - 100
}, 400);
return false;
}
}
Take a look at this JQFAQ post How to select a table cell using click or navigation keys?
this have some thing you want.
Related
I have an application whereby when the user clicks on Add New Item button rows are added dynamically using Javascript and each input field in the row added dynamically has a unique id and this works fine.
When any number on the table on the left is clicked it is populated dynamically in the row on the left. When another number on the table on the right is clicked it populates on the single input on the right (after the plus icon).
When I hover over the 1st row the background color changes to green including the corresponding match on the table on the left which works fine.
Am trying to add a logic whereby
a.) if the user clicks on Add New Item button to add a new row (the row is added according to the format of the 1st row).
b.) After the user clicks on any td number on the 2 tables (right and left) and their values are populates in the rows dynamically (value on the left table populates in the row before + sign and value in the right table populates in the right table after + sign), when the user hovers over the values on the rows their background color should change immediately and conform to the values of the tables they were previously chosen from...
NB ~ Basically I want the behavior on the 1st row (after mouseover when inputs are filled from respective tables) to be simulated across proceeding rows that are added dynamically after the button is clicked.
JsFiddle link: Js Fiddle
~ Kindly assist on this quite challenging task..
Javascript code which is commented to show my steps in the task
//Add row input fields dynamically on button click
// Starting number of inputs
let count = 5;
// Wrapper
const wrapper = document.querySelector("#wrapper");
document.querySelector("#btn").addEventListener("click", () => {
const container = document.createElement("div");
for (let i = 0; i < 5; i++) {
// Increment the count to ensure that it is unique
count++;
// Create new `<input>` element
const input = document.createElement("input");
input.type = "text";
input.name = count;
input.size = "4";
input.id = `inp${count}`;
container.appendChild(input);
// Optional: add empty whitespace after each child
container.append(document.createTextNode(" "));
}
wrapper.appendChild(container);
});
//END creating rows dynamically
let currentInput = 1;
let bonusInput = 1;
//Left table on click event
$("#table1 td").on("click", function(event) {
//gets the number associated with the click
let num = $(this).text();
//Populate it in 1st row input fields (before plus sign)
$("#inp" + currentInput++).attr("value", num);
});
//Right table on click event
$("#table2").on("click", function(event) {
//gets the number associated with the click
let bon = event.target.textContent;
//Populate it in 1st row input fields (after plus sign)
$("#bonus" + bonusInput++).attr("value", bon);
});
//Manipulate background colors of rows with corresponding tables they were
//selected on hover in and hover out
$("input").hover(
function(event) {
let parent = $(this).parent();
$(parent.children()).each(function(index, element) {
let num = $(element).val();
//console.log(num);
if (num) {
//Change input color on hover
$(this).css("backgroundColor", "green");
//Change left table bgcolor on hover
$("#table1 td").each(function() {
if ($(this).text() === num) $(this).css("backgroundColor", "green");
});
// $("#table2 td").each(function() {
// if ($(this).text() === num) $(this).css("backgroundColor","green");
// });
}
});
},
function(event) {
//Change input color on hover out
let parent = $(this).parent();
$(parent.children()).each(function(index, element) {
$(element).css("backgroundColor", "white");
});
//Change left table bgcolor on hover out
$("#table1 td").each(function() {
$(this).css("backgroundColor", "orange");
});
}
);
When you use the .hover()-helper, the event-listeners are created and bound to the items that are available at the moment of creation. All inputs that are created after that are ignored. You have to assign/activate the hover-behaviour for them, when you create/append the new inputs.
//Add row input fields dynamically on button click
// Starting number of inputs
let count = 0;
// Wrapper
const wrapper = document.querySelector('#wrapper');
document.querySelector('#btn').addEventListener('click', () => {
// Increment the count to ensure we have unique inputs
count++;
const container = document.createElement('div');
for (let i = 1; i <= 5; i++) {
let input_index = (count * 5) + i;
// Create new `<input>` element
const input = document.createElement('input');
input.type = 'text';
input.name = input_index;
input.size = '4';
input.id = `inp${input_index}`;
$(input).hover(onInputHoverIn, onInputHoverOut);
container.appendChild(input);
// Optional: add empty whitespace after each child
container.append(document.createTextNode(' '));
}
// Bonus-Input
container.append(document.createTextNode(' + '));
let input_index = count + 1;
// Create new `<input>` element
const input = document.createElement('input');
input.type = 'text';
input.name = `bonus${input_index}`;
input.size = '4';
input.style.marginLeft = '20px';
input.id = `bonus${input_index}`;
$(input).addClass('bonus-input');
$(input).hover(onInputHoverIn, onInputHoverOut);
container.appendChild(input);
wrapper.appendChild(container);
});
//END creating rows dynamically
let currentInput = 0;
let bonusInput = 0;
//Left table on click event
$("#table1 td").on('click',function(event){
if (currentInput >= ((count + 1) * 5)) {
return;
}
currentInput++;
//gets the number associated with the click
let num = $(this).text();
//Populate it in 1st row input fields (before plus sign)
$("#inp" + currentInput).attr("value",num);
});
//Right table on click event
$("#table2").on('click',function(event){
if (bonusInput >= (count + 1)) {
return;
}
bonusInput++;
//gets the number associated with the click
let bon = event.target.textContent;
//Populate it in 1st row input fields (after plus sign)
$("#bonus" + bonusInput).attr("value",bon);
});
//Manipulate background colors of rows with corresponsing tables they were
//selected on on hover in and hover out
function onInputHoverIn(event) {
let parent = $(this).parent();
$(parent.children()).each(function (index, element) {
let num = $(element).val();
let isBonus = $(element).hasClass('bonus-input');
//console.log(num);
if (num) {
//Change input color on hover
$(this).css("backgroundColor","green");
if (!isBonus) {
//Change left table bgcolor on hover
$("#table1 td").each(function() {
if ($(this).text() === num) $(this).css("backgroundColor","green");
});
} else {
//Change left table bgcolor on hover
$("#table2 td").each(function() {
if ($(this).text() === num) $(this).css("backgroundColor","green");
});
}
}
});
}
function onInputHoverOut(event) {
//Change input color on hover out
let parent = $(this).parent();
$(parent.children()).each(function (index, element) {
$(element).css("backgroundColor","white");
});
//Change left table bgcolor on hover out
$("#table1 td, #table2 td").each(function() {
$(this).css("backgroundColor","orange");
});
};
$("input").hover(onInputHoverIn, onInputHoverOut);
table {
border-collapse: collapse;
border: 5px solid black;
width: 100%;
}
td {
width: 50%;
height: 2em;
border: 1px solid #ccc;
background-color:orange;
text-align:center;
vertical-align:middle;
font-weight:bold;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--Table on the left -->
<div style="width: 140px; float: left;">
<table id="table1">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
<!-- Rows on the right-->
<!--2nd table-->
<div style="width: 140px; float: left; margin-left: 12px;">
<table id="table2">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
<!-- Rows on the right-->
<!-- Make sure each input has a unique id-->
<div style="clear: both;">
<div id="wrapper">
<div>
<input type="text" name="1" size="4" id="inp1" value="">
<input type="text" name="2" size="4" id="inp2" value="">
<input type="text" name="3" size="4" id="inp3" value="">
<input type="text" name="4" size="4" id="inp4" value="">
<input type="text" name="5" size="4" id="inp5" value=""> +
<input class="bonus-input" style="margin-left: 20px;" type="text" name="bonus1" size="4" id="bonus1" value="">
</div>
</div>
<button type="button" id="btn">Add new input group</button>
</div>
Given this table:
<table class="tbllist searchtbl" cellpadding=2 cellspacing=0 style="width: 70%">
<tr>
<th class="hidden">ID</th>
<th>Number Plate</th>
<th>Chassis Number</th>
<th>Trailer Make</th>
<th>Year</th>
<th>Axles</th>
<th></th>
</tr>
<tr class='tbl'>
<td class='hidden'>3</td>
<td>
<input type=text style = 'width: 75px' class='centered' id='trnumberplate_3' name='trnumberplate_3' value='T212ABS' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trnumberplate", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 200px' id='trchassisnumber_3' name='trchassisnumber_3' value='AJSDGASJH' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trchassisnumber", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 200px' id='trmake_3' name='trmake_3' value='LOW LOADER' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trmake", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 50px' class='centered' id='tryear_3' name='tryear_3' value='2009' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","tryear", this.value ,"trid","3","1","",this, "false")'>
</td>
<td>
<input type=text style = 'width: 25px' class='centered' id='traxles_3' name='traxles_3' value='3' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","traxles", this.value ,"trid","3","1","",this, "false")'>
</td>
<td class='delbtn'>
<button id='trailers_3' title='DELETE THIS ITEM (3)?' onclick='event.preventDefault(); delitem("trailers","trid","3","trailers.php","#workspace")'><img src='/icons/delete.png' ></button>
</td>
</tr>
</table>
I have the following search function:
function searchbox() {
// text input search for tables (such as trip history etc)
$("#search").keyup(function () {
//split the current value of searchInput
var data = this.value.toUpperCase().split(" ");
//create a jquery object of the rows
var jo = $(".tbllist").find("tr").not("tr:first"); // exclude headers
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
})
It will loop through table td's to check if the searched value is available and filter rows. It is not filtering if the td contains an input text element with the searched value.
Update:
if ($t.find("input").val().toUpperCase().indexOf(data[d]) > 0) {
return true;
}
Now works but will only matches the first column of the table.
JSFiddle: https://jsfiddle.net/fabriziomazzoni79/30d52c9z/
Change jo.filter() like this:
jo.filter(function (i, v) {
var txt = '';
$(v).find("input").each(function(n,e){
txt += e.value;
});
for(var d=0; d<data.length; d++){
if (txt.search(data[d])>=0) {
return true;
}
}
return false;
})
Fiddle here.
So this is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body{font-family:Arial, Helvetica, sans-serif;font-size:12px;}
table{width:700px;margin:auto;border:solid 5px #cccccc}
table th{border-right:solid 1px #cccccc;border-bottom:solid 1px #000000;padding:5px;}
table th:last-child{border-right:0px;}
table td{border-right:solid 1px #d0d7e5;border-bottom:solid 1px #d0d7e5;}
table td:last-child{border-right:0px;}
table tr:last-child td{border-bottom:0px;}
table td input{padding:5px 0px;margin:auto;white-space:nowrap;overflow:hidden;outline:none;border:solid 1px #ffffff;text-align:center;width:99%;}
table td input.green{background:#00b050;border:solid 1px #00b050;}
table td input.red{background:#ff0000;border:solid 1px #ff0000;}
table td.active input{border:dotted 1px #333333;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var row_template = "<tr><td><input type='text' value='0.00' maxlength='5' /></td><td><input type='text' value='0.00' maxlength='5' /></td><td><input type='text' value='0.00' maxlength='5' /></td></tr>";
var active_row;
var active_col;
// Initialize cell width
//$("table td").each(function()
//{
//var width = $(this).width();
//$(this).find("input").width(width-2);
//});
//----------------------
// Set Focus of cell
$("table").on("focus", "tr td input", function()
{
var row_count = $("table tr").size()-1;
$("table td").removeClass();
active_col = $(this).closest("td").index()+1;
active_row = $(this).closest("tr").index();
$(this).parent().addClass("active");
$(this).val("");
if(active_row == row_count)
{
$("table").append(row_template);
}
});
//------------------
// Set Blue of cell
$("table").on("blur", "tr td input", function(e)
{
var value = $(this).val();
if(isNaN(value) || value == "")
{
value = 0;
}
$(this).val(parseFloat(value).toFixed(2));
format_cell(active_row, active_col);
});
//-----------------
// Enter key on cell
$("table").on("keydown", "tr td input", function(e)
{
var value = $(this).val();
if(e.keyCode == 13)
{
$(this).blur();
if(active_col == 2)
{
$("table tr").eq(active_row).find("td").eq(active_col).find("input").focus();
}
else if(active_col == 3)
{
$("table tr").eq(active_row+1).find("td").eq(active_col-2).find("input").focus();
}
return(false);
}
else
{
if(value.length == 2)
{
$(this).val(value+".");
}
}
});
//------------------
// Download data
$("#btn_download").click(function()
{
var json = "";
var movement;
var pdi;
var ndi;
json += "[";
json += '{"movement":"Movement","pdi":"PDI","ndi":"NDI"},';
$("table tr:gt(0)").each(function(r)
{
movement = $(this).find("td").eq(0).find("input").val();
pdi = $(this).find("td").eq(1).find("input").val();
ndi = $(this).find("td").eq(2).find("input").val();
movement = (movement==0?"0":movement);
pdi = (pdi==0?"0":pdi);
ndi = (ndi==0?"0":ndi);
if(r==0)
{
json += '{"movement":"'+movement+'","pdi":"'+pdi+'","ndi":"'+ndi+'"}';
}
else
{
json += ',{"movement":"'+movement+'","pdi":"'+pdi+'","ndi":"'+ndi+'"}';
}
});
json += "]";
var csv = json_to_csv(json);
window.open("data:text/csv;charset=utf-8," + escape(csv));
});
//--------------
});
function format_cell(row, col, pre_value)
{
var pre_value = $("table tr").eq(row-1).find("td").eq(col-1).find("input").val();
var value = $("table tr").eq(row).find("td").eq(col-1).find("input").val();
if(col == 3)
{
if(parseFloat(value) < parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("red").addClass("green");
}
else if(parseFloat(value) > parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green").addClass("red");
}
else
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green red");
}
}
else
{
if(parseFloat(value) > parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("red").addClass("green");
}
else if(parseFloat(value) < parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green").addClass("red");
}
else
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green red");
}
}
calculate_grid();
}
function calculate_grid()
{
$("table tr:gt(0)").each(function(r)
{
var pdi = $(this).find("td").eq(1).find("input").val();
var ndi = $(this).find("td").eq(2).find("input").val();
var movement = (parseFloat(pdi) - parseFloat(ndi)).toFixed(2);
r=r+1;
$(this).find("td").eq(0).find("input").val(movement);
if(movement > 0)
{
$(this).find("td").eq(0).find("input").removeClass("red").addClass("green");
}
else if(movement < 0)
{
$(this).find("td").eq(0).find("input").removeClass("green").addClass("red");
}
else
{
$(this).find("td").eq(0).find("input").removeClass("green red");
}
});
}
function json_to_csv(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = "";
var line = "";
if($("#labels").is(':checked'))
{
var head = array[0];
if($("#quote").is(':checked'))
{
for(var index in array[0])
{
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
}
else
{
for(var index in array[0])
{
line += index + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
for(var i=0;i<array.length;i++)
{
var line = "";
if ($("#quote").is(':checked'))
{
for (var index in array[i])
{
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
}
else
{
for(var index in array[i])
{
line += array[i][index] + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
return(str);
}
</script>
<title>Excel</title>
</head>
<body>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<th width="30%">Movement Data</th>
<th width="35%">PDI</th>
<th width="35%">NDI</th>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
</table>
<center><input type="button" id="btn_download" value="Download" /></center>
</body>
</html>
I want to change color in the movement cell according to the data. If the the current value is lower than the preceding value I want it to be red and if the current value is more than the preceding value than I want it to be green. I believe it requires a minor change in the "movement function"
Please help.
Here is a jsfiddle for the scenario: Click Here
Is this not what already happens. I have tested the jsfiddle (http://jsfiddle.net/4QBwK/), behaviour seems a little odd, but I think it fits what you have specified.
The only change I think is needed is to remove most of the code from the format_cell() function that seems to randomly light up cells in either red or green. I have commented it out on this jsfiddle: http://jsfiddle.net/4QBwK/1/
So you would just have this instead:
function format_cell(row, col, pre_value)
{
calculate_grid();
}
I have an HTML table with insert and delete row functionality and its working perfectly. But delete functionality works with checkbox + delete button.
When i want to delete a row, first i checked the checkbox and then press delete button. I want to make it directly with delete button. Below is my code,
function deleteRow(tableID)
{
try
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++)
{
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked)
{
if (rowCount <= 1)
{
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch(e)
{
alert(e);
}
getValues();
}
<a onclick="deleteRow('dataTable')">Delete Row</a>
<table id="dataTable">
<tr>
<td><input type="checkbox" name="chk"/></td>
<td><input type="text" name="Name"></td>
</tr>
</table>
Note : Atleast 1 row should be there (Cannot delete all the rows)
If you want to use one button, a usable solution is to select/unselect the rows to be deleted onclick. This way multi select and delete is also supported. For example,
http://jsfiddle.net/Nt4wZ/
js
function selectRow(row) {
if (row.className.indexOf("selected") != -1) {
row.className = row.className.replace("selected", "");
} else {
row.className += " selected";
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
/*var chkbox = row.cells[0].childNodes[0];*/
/*if (null != chkbox && true == chkbox.checked)*/
if (row.getElementsByTagName("input")[0].className.indexOf("selected")!=-1) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
//getValues();
}
html
<a onclick="deleteRow('dataTable')">Delete Row</a>
<table id="dataTable">
<tr>
<!-- <td><input type="checkbox" name="chk"/></td> -->
<td>
<input type="text" name="Name" onclick="selectRow(this)" />
</td>
</tr>
<tr>
<!-- <td><input type="checkbox" name="chk"/></td> -->
<td>
<input type="text" name="Name" onclick="selectRow(this)" />
</td>
</tr>
</table>
css
input.selected {
border-color:lightgreen;
}
EDIT - response to comments
If you want to have a delete button for each row and use that instead, you can do something like the following,
http://jsfiddle.net/GRgMb/
html
<table id="dataTable">
<tr>
<!-- <td><input type="checkbox" name="chk"/></td> -->
<td>
<input type="text" name="Name" /><input type="button" value="delete" onclick="deleteRow('dataTable',this)" />
</td>
</tr>
<tr>
<!-- <td><input type="checkbox" name="chk"/></td> -->
<td>
<input type="text" name="Name" /><input type="button" value="delete" onclick="deleteRow('dataTable',this)" />
</td>
</tr>
</table>
js
function deleteRow(tableID,currentRow) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
/*var chkbox = row.cells[0].childNodes[0];*/
/*if (null != chkbox && true == chkbox.checked)*/
if (row==currentRow.parentNode.parentNode) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
//getValues();
}
This code is an example:
$(document).on('click', 'img.imgdel', function deleteRow() {
$(this).closest('tr').remove();
return false;
});
https://codepen.io/dionejpmc/pen/vYxLdyX
I need your help.
Because of the way IE7 chooses to ignore the TD: whitespace: nowrap, I am forced to put and use spans in front of my TD's so here's the delema. When I click on a table row that has no spans in between the td's, the coding is able to extract the data and highlight the row.
However, when I introduce a span in between my td's and click to select a single cell in the table row with the spans's I get the following error: "cells.0 is null or not an object." I know that if I click a little bit off the side of the table cell it works, but I need to be able to also click on the <TD> and <SPAN> areas and have the code work.
Since I am making a table that will have all <span></span>'s in between all the <TD>'s how can the existing coding be reformatted to accomodate the difference from <td>data</td> to <td><span>data</span></td>?
No jQuery please.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#data tr.normal td {
color: #235A81;
background-color: white;
}
#data tr.highlighted td {
color: #FFFFFF;
background-color: #235A81;
}
</style>
<script type='text/javascript'>
function test() {
var table = document.getElementById("data");
var thead = table.getElementsByTagName("thead")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var ishigh
tbody.onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement
var row = td.parentNode;
if (ishigh&&ishigh!=row){
ishigh.className='';
}
row.className = row.className==="highlighted" ? "" : "highlighted";
ishigh=row;
getdata(row)
}
document.onkeydown = function(e){
e = e || event;
var code = e.keyCode, rowslim = table.rows.length - 2, newhigh;
if(code === 38){ //up arraow
newhigh = rowindex(ishigh) - 2;
if(!ishigh || newhigh < 0){return GoTo('data', rowslim);}
return GoTo('data', newhigh);
} else if (code === 40){ //down arrow
newhigh = rowindex(ishigh);
if(!ishigh || newhigh > rowslim){return GoTo('data', 0);}
return GoTo('data', newhigh);
}
}
function GoTo(id,nu){
var obj=document.getElementById(id),
trs=obj.getElementsByTagName('TR');
nu = nu + 1;
if (trs[nu]){
if (ishigh&&ishigh!=trs[nu]){
ishigh.className='';
}
trs[nu].className = trs[nu].className=="highlighted" ? "" : "highlighted";
ishigh=trs[nu];
}
getdata(trs[nu]);
}
function rowindex(row){
var rows = table.rows, i = rows.length;
while(--i > -1){
if(rows[i] === row){return i;}
}
}
function getdata(row) {
document.getElementById('firstname').value = row.cells[0].innerHTML;
document.getElementById('lastname').value = row.cells[1].innerHTML;
document.getElementById('age').value = row.cells[2].innerHTML;
document.getElementById('total').value = row.cells[3].innerHTML;
document.getElementById('discount').value = row.cells[4].innerHTML;
document.getElementById('diff').value = row.cells[5].innerHTML;
find_option('fname',row.cells[0].innerHTML)
}
}//end of nested function
function find_option(id,value) {
var sel = document.getElementById(id)
for (var i = 0; i < sel.length; i++){
//alert(sel.options[i].text+" "+sel.options[i].value)
if (sel.options[i].value == value) {
sel.selectedIndex = i;
return
}
}
}
</script>
</head>
<body>
<table id="data" cellspacing="1" border="1">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>age</th>
<th>total</th>
<th>discount</th>
<th>diff</th>
</tr>
</thead>
<tbody>
<tr>
<td><span>peter</span></td>
<td><span>parker</span></td>
<td><span>28</span></td>
<td><span>9.99</span></td>
<td><span>20.3%</span></td>
<td><span>+3</span></td>
</tr>
<tr>
<td>john</td>
<td>hood</td>
<td>33</td>
<td>19.99</td>
<td>25.1%</td>
<td>-7</td>
</tr>
<tr>
<td>clark</td>
<td>kent</td>
<td>18</td>
<td>15.89</td>
<td>44.2%</td>
<td>-15</td>
</tr>
<tr>
<td>bruce</td>
<td>almighty</td>
<td>45</td>
<td>153.19</td>
<td>44%</td>
<td>+19</td>
</tr>
<tr>
<td>benjamin</td>
<td>evans</td>
<td>56</td>
<td>153.19</td>
<td>23%</td>
<td>+9</td>
</tr>
</tbody>
</table>
<br>
Firstname is:
<input type="text" id="firstname" />
<br>Lastname is:
<input type="text" id="lastname" />
<br>Age is:
<input type="text" id="age" />
<br>Total is:
<input type="text" id="total" />
<br>Discount is:
<input type="text" id="discount" />
<br>Diff is:
<input type="text" id="diff" />
<br>
<input type="button" value="testme" onclick="test()">
<br><br>
<select id="fname">
<option value="bruce">bruce</option>
<option value="clark">clark</option>
<option value="benjamin">benjamin</option>
</select>
</body>
</html>
Change this line:
var row = td.parentNode;
to:
var row = (td.tagName == "DIV") ? td.parentNode.parentNode : td.parentNode;
You can look at the elemet's tag name and determine whether the user has clicked on a TD or a SPAN, then adjust select the element's parent (the TD) if you have a span.
var td = e.target || e.srcElement
alert(td.tagName)
Alternately, you can add a CSS class name to all of your SPANS and then check to see if the selected element has that class name. If it does, it's a SPAN, if it doesn't, it's a TD.
I would also suggest using a DIV, not a SPAN.