How to highlighted the selected row from repeater? - javascript

I have a repeater, and i just want that when i select or click on any row of it then that would be highlighted. I had tried some code of javascript which makes the selected row highlighted, but not unhighlighting when select any other row.My code is:-
<tr id="gh" style="cursor: pointer" onclick="Select(this);">
any javascript's and style's code is:-
<style type="text/css">
.highlight
{
background-color: Red;
}
.selected
{
background-color: #ffdc87;
}
</style>
<script type="text/javascript">
function Select(obj) {
obj.className = 'selected';
var tbl = document.getElementById("Repaddressorbbl")
var firstRow = tbl.getElementsByTagName("TR")[0];
var tableRowId = tbl.rows[firstRow.getElementById("gh").parentNode.id];
alert(tableRowId);
var oldRow = tbl.rows[firstRow.getElementsByTagName("tr")[0].value];
if (oldRow != null) {
oldRow.className = '';
}
firstRow.getElementsByTagName("tr")[0].value = obj.rowIndex;
}
</script>
We can do it simply with code behind but the matter is it should be done only with jquery or javascript.

You can use code similar to this:
var INDEX = $(this).parent().children().index($(this));
$('#Repaddressorbbl tr:nth-child(' + INDEX + ')').addClass("highlight")
.siblings()
.removeClass("highlight"); // remove css class from other rows
It gets the rownumber of the TR and adds a CSS class while removing the same class from all other TRs.

i've added a function to select elements with a specific classname so you can easly search the dom for elements with that class
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
function Select(obj) {
var oldRow = document.getElementsByClassName('selected');
if(oldRow.length > 0)
oldRow[0].className = '';
obj.className = 'selected';
}

Update for jQuery:
$(document).ready(function() {
$("tr").click(function() {
$(this).addClass("highlight").siblings().removeClass("highlight");
}
}
Original answer:
If I understand you correctly, all of your table rows are defined like this:
<tr id="gh" style="cursor: pointer" onclick="Select(this);">
And you want to set a class on the most recently clicked row so it looks selected, while clearing said class from the previously clicked/selected row?
If so, a much simplified version of your function should do it:
var selectedRow = null;
function Select(obj) {
if (obj != selectedRow) {
if (selectedRow != null) {
selectedRow.className = '';
}
obj.className = 'selected';
selectedRow = obj;
}
}
I don't understand what you're trying to do with the firstRow.getElementsByTagName("tr") stuff. Have you got nested tables?

Related

I have 3 Data tables in one page i need select one in each Table

I am trying following it selecting from only one datatable
selectFirstRow(window.document.forms["irsf-form"]);
i have id's for each table "test_config","uma","example".
i had tried
selectFirstRowInTable(document.getElementById("irsf-form:test_config"));
selectFirstRowInTable(document.getElementById("irsf-form:uma"));
selectFirstRowInTable(document.getElementById("irsf-form:example"));
I have Script in that
function selectFirstRowInTable(tableObj) {
var tbodyObj = tableObj.getElementsByTagName("tbody")[0];
var inputObjs = tbodyObj.getElementsByTagName("input");
var tempChild = null;
var firstRow=-1;
for(var i=0;i<inputObjs.length;++i) {
tempChild = inputObjs[i];
if(tempChild.type == 'radio') {
if ( firstRow < 0 ) {
firstRow = i;
tempChild.checked = true;
} else {
tempChild.checked = false;
}
}
}
}
Not getting the value by id when i try getElementById
<h:dataTable binding="#{iRSFConfigBean.table}" border="1" rowClasses="evenRows,oddRows" id="test_config" name = "test"
rules="all" headerClass="standardTableHeader" styleClass="standardTable" value="#{iRSFConfigBean.configList}" var="config">
Hope this code will help you:
$('table').find("tr:first")

How to display one row from a HTML table and change to next?

I have a HTML table with 2 columns, 5 rows.
you can do this:
function findMyRow(el)(){
if(!el.parentNode) return null;
else if(el.parentNode.tagName.toLowerCase()=="tr") return el.parentNode;
else return findMyRow(el.parentNode);
}
for(var i=0;i<tbl.rows.length;i++){
tbl.rows[i].onclick = function(e){
var selectedRow = null;
if(e.target.tagName.toLowerCase()=="tr") selectedRow = e.target;
selectedRow = findMyRow(e.target);
//this is just for preventing false event raising
if(!selectedRow) return false;
var rowIndex = Array.prototype.indexOf.call(tbl.rows, selectedRow);
for(car j=0;j<selectedRow.cells.length;j++){
var cell = selectedRow.cells[j];
//let's say your inputs each has an unique ID based on your columns index
//like <input id="cellData0" ttype="text" />
//or <input id="cellData1" ttype="text" /> and so on
document.getElementById("cellData" + j).value = cell.innerText;
}
}
}
although you can do this more easier than with jQuery.
With Jquery you could do something like:
$(document).ready(function(){
window.rowIndex = 0; // gobal variable
function displayRow(){
var tableRows = $('#mytable tr');
if(tableRows.length <= window.rowIndex) {
window.rowIndex = 0;
}
var rowCells = $(tableRows[window.rowIndex]).find('td');
$('.cellone').val($(rowCells[0]).html());
$('.celltwo').val($(rowCells[1]).html());
window.rowIndex = window.rowIndex + 1;
};
$('.next').click(function(event){ displayRow(); });
displayRow();
});
There is a live demo here Hope it helps!

Toggle table row visibility based on presence of td class

How can I toggle multiple rows in a table if the <td> class is set to an specific class. For instance toggle all rows if they contain the class="foo".
<table id="bar">
<tr>
<td>hello</td>
<td class="foo">there</td>
<td class="foo">bye</td>
</tr>
</table>
Here's a non-jQuery solution, written just for you: http://phrogz.net/tmp/toggling_rows_with_class.html
Here's the relevant JS:
window.onload = function() {
var visible = true;
document.getElementById('toggle').onclick = function() {
visible = !visible;
var tds = findElementsWithClass('td', 'foo');
for (var i=0, len=tds.length; i<len; ++i) {
tds[i].parentNode.style.display = visible ? '' : 'none';
}
};
}
function findElementsWithClass(tagName, className) {
if (document.querySelectorAll) {
return document.querySelectorAll(tagName + "." + className);
} else {
var results = [];
var all = document.getElementsByTagName(tagName);
var regex = new Regexp("(?:^|\\s)" + tagName + "(?:\\s|$)");
for (var i=0, len=all.length; i<len; ++i) {
if (regex.test(all[i].className)) {
results.push(all[i]);
}
}
return results;
}
}
Modify the class
Why is everyone using selectors? There is already a class attached to all the appropriate elements, so why not just modify the class?
This function will find the class of a given name, and set an attribute for that class. Be careful if you have multiple classes with coincident names in different stylesheets, because the function isn't!
function changeStyle(stylename,attribute,newvalue) {
var cssRules = 'rules';
if(document.styleSheets[0].cssRules) {
cssRules = 'cssRules';
}
for(var sheetId=0; sheetId<document.styleSheets.length; sheetId++) {
var sheet = document.styleSheets[sheetId];
for(var ruleId=0; ruleId<sheet[cssRules].length; ruleId++) {
var rule = sheet[cssRules][ruleId];
if(rule.selectorText == "."+stylename) {
rule.style.setProperty(attribute,newvalue,"");
}
}
}
return false;
}
Now, just call
changeStyle('foo','display','none');
and the cells should disappear, then with 'block' to get them back (IE can't do the more recent display styles like ). I suspect that in a table you'll want to hide entire rows rather than just cells, but you can also make them disappear by setting visibility to hidden - they will still take up space, but not draw.
See, no jquery, no homemade element selectors. Just a slightly annoying bit of javascript to loop through the stylesheets and their rules...
td = document.getElementsByTagName('td');
for (var i = 0; i < td.length; i++) {
if (td[i].className === 'foo')
if (!td[i].style.display)
td[i].style.display = 'none';
else
td[i].style.display = '';
}
}
http://jsfiddle.net/qwertymk/cyZn9/2/
Something like this should do it:
var trs = document.getElementsByTagName("tr");
for (var i in trs) {
var tr = trs[i];
if (tr.getElementsByClassName("foo").length > 0)
tr.style.display = (tr.style.display == "none" ? "block" : "none");
}
This will toggle the display on any TR that contains a child with class="foo".
Something like this?
$("table td.specific_class").toggle();
Edit
/* Go through the table rows */
var trs = document.getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++ ) {
var myClass, tds, line_done = false;
/* Go through the table cells */
tds = trs[i].getElementsByTagName("td");
for ( var k = 0; k < tds.length; k++ ){
/* Check each class of each cell */
myClasses = tds[k].className.split(' ');
for ( var j = 0; j < myClasses.length; j++ ){
/* If the class corresponds we toggle the row and break until the next row */
if ( myClasses[j].className == "foo" ){
trs[i].style.display = trs[i].style.display == "none" ? "block" : "none";
line_done = 1;
break;
}
}
if ( line_done ){
break;
}
}
}
try this one
<html>
<head>
<title>test</title>
<script type="text/javascript">
var toggle = function (action) {
var trs = document.getElementById('bar').getElementsByTagName('tr'),
trs_count = trs.length,
needed = [],
total = 0,
pattern = /\bfoo\b/g,
initial= 'show';
for (i=0; i<trs_count; i++) {
var tds = trs[i].getElementsByTagName('td'),
tds_count = tds.length;
for (j=0; j<tds_count; j++) {
if (pattern.exec(tds[j].className)) {
needed.push(tds[j]);
total++;
}
}
}
toggle = function (action) {
if (this.display == null) {
this.display = initial;
}
if (action == null) {
this.display = (this.display == 'hide') ? 'show' : 'hide';
}
else {
this.display = action;
}
for (i=0; i<total; i++) {
if (this.display == 'show') {
needed[i].style.display = 'block';
}
else {
needed[i].style.display = 'none';
}
}
return true;
}
return toggle();
}
</script>
</head>
<body>
<table id="bar">
<tr><th>Header</th></tr>
<tr><td class="foo">1 Data foo</td></tr>
<tr><td>2 Data</td></tr>
<tr><td class="foo">3 Data foo</td></tr>
<tr><td>4 Data</td></tr>
</table>
<button type="button" onclick="toggle()">toggle</button>
</body>
</html>

Making a row editable based on a checkbox in HTML

I have a table in HTML. The contents of this table are dynamically populated. Every row of the table has text boxes and one checkbox. When the page is loaded, all the text boxes in the rows will be in a read-only state.
Now, i want to change the state of the text boxes in a particular row to editable, if the check-box in that row is selected. Also, the text boxes should be made read-only if the check box is de-selected.
How could I accomplish this using Javascript? Please help me.
stating this with plain javascript would be pure pain :)
i suggest using jQuery, eg:
$(':checkbox').click(function() {
var checkbox = $(this);
var row = checkbox.closest('tr');
var inputText = $('input[type=text]', row);
if (checkbox.is(':checked')) {
inputText.attr('readonly', 'readonly');
}
else {
inputText.removeAttr('readonly');
}
});
otherwise
function HandleClickOnCheckbox() {
var checkbox = this;
var row;
var iter = checkbox;
while (!row) {
iter = iter.parent;
if (iter == window) {
break;
}
if (iter.tagName == 'tr') {
row = iter;
break;
}
}
if (!row) {
alert('row not found');
return false;
}
var textBoxes = GetTextBoxes(row);
var method;
if (checkbox.checked) {
var disabledAttribute = document.createAttribute('disabled');
disabledAttribute.nodeValue = 'disabled';
method = function(textBox) {
textBox.setAttributeNode(disabledAttribute);
};
}
else {
method = function(textBox) {
textBox.removeAttribute('disabled', 0);
}
}
for (var i = 0; i < textBoxes.length; i++) {
var textBox = textBoxes[i];
method(textBox);
}
}
function GetTextBoxes(element) {
var textBoxes = new Array();
for (var i = 0; i < element.children.lenght; i++) {
var child = element.children[i];
if (child.tagName == 'input') {
if (child.type == 'text') {
textBoxes.push(child);
}
}
if (child.tagName == 'td') {
var childTextBoxes = GetTextBoxes(child);
if (childTextBoxes.length) {
for (var j = 0; j < childTextBoxes.length; j++) {
var childTextBox = childTextBoxes[j];
textBoxes.push(childTextBox);
}
}
}
}
return textBoxes;
}
this is not tested!
Perhaps, you can start by handling the click event of the checkbox using an if/else statement to check if the checkbox is actually checked. If it is you can use the row within which the checkbox resides to find all the textboxes in the different cells and enable/disable them.
Are you using JQuery or plain Javascript?
If you don't mind using jQuery, you could do:
$('checkbox').click(function() {
if ($(this).attr('checked')) {
$(this).parents('tr').children('input[type="text"]').each().attr('readonly', 'readonly');
} else {
$(this).parents('tr').children('input[type="text"]').each().removeAttr('readonly');
}
})
Or something like that. I'd have to test it to be sure.
Edited to reflect Andreas's comment.
Try this snippet (assumes that the checkbox has a class called "checkbox") if you are using Jquery.
jQuery('tr.checkbox').click(function() {
if (jQuery(this).is(":checked")) {
jQuery('td', this).removeAttr('disabled');
} else {
jQuery('td', this).attr('disabled', '');
}
});`

How do I remove an element from the DOM, given its id?

In this specific case, the element is a table row.
Untested but something like:
var tbl = document.getElementById('tableID');
var row = document.getElementById('rowID');
tbl.removeChild(row);
or
var row = document.getElementById('rowID');
row.parentNode.removeChild(row);
var row = document.getElementById("row-id");
row.parentNode.removeChild(row);
var zTag = document.getElementById ('TableRowID');
zTag.parentNode.removeChild (zTag);
Or in jQuery:
$('#TableRowID').remove ();
Jquery
$('#myTableRow').remove();
This works fine if your row has an id, such as:
<tr id="myTableRow"><td>blah</td></tr>
Pure Javascript :
Javascript Remove Row From Table
function removeRow(id) {
var tr = document.getElementById(id);
if (tr) {
if (tr.nodeName == 'TR') {
var tbl = tr; // Look up the hierarchy for TABLE
while (tbl != document && tbl.nodeName != 'TABLE') {
tbl = tbl.parentNode;
}
if (tbl && tbl.nodeName == 'TABLE') {
while (tr.hasChildNodes()) {
tr.removeChild( tr.lastChild );
}
tr.parentNode.removeChild( tr );
}
} else {
alert( 'Specified document element is not a TR. id=' + id );
}
} else {
alert( 'Specified document element is not found. id=' + id );
}
}

Categories

Resources