Friday, May 8, 2015

Toggle Enabled State on Submit Button from Checkbox with jQuery

$("#myCheckBox").change(function () {
        $("input[type='submit']").prop("disabled", !this.checked);        
    });

Friday, March 21, 2014

How to Change HTML Table Cell Value

First, we need to get a reference to a table cell value.

var table = document.getElementById('myTableId');

An HTMLTableElement has a rows property that refers to the table rows collection. An HTMLTableRowElement has a cells property that refers to the row cells collection.

With this information at hand it is easy to get a reference to any cell.

Let's say, we need to refer to the first column of the first row.

Since the collection index starts at 0 we can get this reference using the following code:

var cell = table.rows[0].cells[0];

The cell variable now refers to the cell in the first column and first row.
The data in the table cell is represented by a text node. We can get a reference to it by using the firstChild property of an HTMLElement.

We obtain a reference to the text node value by using its data property.

var value = cell.firstChild.data;

Now it is easy to change the text in a table cell:

cell.firstChild.data = 'my new text';

What if you have an HTML object in your data cell, like a radio button ? In this case, 'firstChild' property will refer to this object, and you can get all the properties of the object by referring to the cell's firstChild property, e.g:

cell.firstChild.value
cell.firstChild.name
cell.firstChild.type
 

Change table cell value automatically


To change a table cell value automatically we must assign an event handler to the cell onblur event.

For DOM scripting, I would recommend an excellent book on the subject by Jeremy Keith DOM Scripting: Web Design with JavaScript and the Document Object Model. It will teach you to work with DOM and JavaScript from the ground up.

 Some other posts you might find interesting:

How to Hightlight Table Rows

Extract Table Text

Sunday, September 23, 2012

Format Number with a Thousand Separator

Here are a couple of helpful functions to work with number.
The first one formats a number with a thousand separator. A comma is used as a thousands separator.


function format(obj){
  var str = obj.toString();
  var re=/(-?\d+)(\d{3})/;
  while(re.test(str)){
   str=str.replace(re,'$1,$2')
  }
  return str;
}

This one removes formatting:
function deformat(str){
 var re = /,/g;
   return str.replace(re,'');
}

Tuesday, May 1, 2012

Extract Table Text

The following recursive function can be used to extract text from any HTML element including a table.

var cnts= '';
function getElementText(el){
 var cn=el.childNodes,i;
 if(el.nodeType==3){
     cnts += (el.nodeValue + "\n");
 }
 for(i=0;i<cn.length;++i)
   getElementText(cn[i]);
}

The function accepts an HTML object as a parameter. First it checks for the nodeType property of the DOM element. If the nodeType value is 3 (TEXT_NODE) the function grabs the element text (nodeValue) and appends it to the global variable cnts. As the final step the function calls itself supplying each element child as the parameter.  The only downside I see is using a global variable to hold the element contents. But so far I don't see any other way to achieve the same functionality.

An interesting article about anonymous recursive functions can be found here.

Another post you might find interesting:  Hide Columns in a Table

Thursday, March 29, 2012

Edit Table Cell in Place

Let's create a function that will get a reference to a table cell as a parameter, and make the table cell editable. In other words, create Edit In Place. Our function will be very simple, and use only standard DOM methods. It will be called by clicking on the table cell.
 function makeEditable(el){
 }
The el variable will hold a reference to a table cell. Normally, a table cell will have one childNode - the text element. First we check whether this is the first click on the table cell:
  if(el.firstChild.nodeName !="INPUT"){
  }
If it is so, we create an input element:
 var input = document.createElement("INPUT");
Assign the value of the cell text to the input element and set different background:
 input.value = el.firstChild.nodeValue;
   input.style.background = "rgb(255,244,255)";
Turn autocomplete off to avoid the 'Permission denied to set property XULElement.selectedIndex' error in Firefox.
 input.setAttribute('autocomplete','off');
Replace the text with the input element we just created and set focus on it:
  el.replaceChild(input, el.firstChild);
  el.firstChild.select();
  el.firstChild.focus();
To turn the input element back into text, we'll do the reverse procedure - create a text node, and replace the input element with text:
 var text= document.createTextNode(el.firstChild.value);
 el.replaceChild(text, el.firstChild);
The function will called from a cell element as follows:
onclick=makeEditable; 


Once a user turned the input back into text, you could apply various Ajax techniques to save the modified text on the server.

Here is the full function listing:

function makeEditable(){
 var el = this;
 if(el.firstChild.nodeName !="INPUT"){
   var input = document.createElement("input");
    input.value = el.firstChild.nodeValue;
    input.setAttribute('autocomplete','off');
    input.style.background = "rgb(255,244,255)";
    el.replaceChild(input, el.firstChild);
    el.firstChild.select();
    el.firstChild.focus();
   }
   else{
    var text= document.createTextNode(el.firstChild.value);
  el.replaceChild(text, el.firstChild);
   }
 }

When the makeEditable function is called from a table cell, the keyword this in the function refers to the table cell element.

Unobtrusive JavaScript

There is a way to attach a function to the onclick event in each table cell without having to write inline code. Here is how to do it:

function addEventHandlers() {
  //the table should have an id
  var table = document.getElementById('example');
  var tds = table.getElementsByTagName('td');
  for(var i=0; i< tds.length; i++){
   //no brackets after the function name
   tds[i].onclick = makeEditable;
   tds[i].title = 'Click to edit';
  }
}

The last step is to make sure this function is called after a page has loaded:
 
window.onload = addEventHandlers;
-->

Related posts:

How to Change HTML Table Cell Value

Hide Columns in a Table

Wednesday, March 28, 2012

Delete Table Rows

To delete selected rows from a table, obviously, we need to add checkboxes to every table row. When a checkbox is checked, it means that that particular row will be deleted. Also, we need some method by which we could identify a selected row. The value attribute of a checkbox is a very good candidate for that. It will equal a row index. As you know, row indices start at 0, so the value of first row checkbox will equal 0, the value of the second row checkbox will equal 1, and so on.
Now, we can write a function to be called from the Delete button:
First, we get a reference to the table:

var table = document.getElementById("myTable");

Then, we get a reference to the array of checkboxes in the table:

var checks = table.getElementsByTagName("input");

Normally, this array will contain all the inputs in the table, and we would have to use the type property to get a reference to desired elements. However, if we are sure that there are no other inputs in the table other than the checkboxes, we can skip this check.
Now, we iterate through all the checkboxes. If the checked property is true, we obtain the index of a row which is contained in the checkbox value property, and delete this row. Also, we have iterate backwards, because otherwise removing a row changes the subsequent row index by -1. Iterating backwards preserves our indices.

for(var i= checks.length-1; i>=0; i --){
 if(checks[i].checked){
  var indx =  checks[i].value;
  table.deleteRow(indx);
 }
}

The next step resets the values of the checkboxes to make sure that they correspond to the new row indices.

var checks = table.getElementsByTagName("input");
for(var i= 0; i < checks.length; i++){
 checks[i].value=i;
}

Here is the complete function listing :

function deleteRows(){
 var table = document.getElementById("myTable");
 var checks = table.getElementsByTagName("input");

 for(var i= checks.length-1; i>=0; i --){
  if(checks[i].checked){
   var indx =  checks[i].value;
   table.deleteRow(indx);
  }
 }
 var checks = table.getElementsByTagName("input");
 for(var i= 0; i < checks.length; i++){
  checks[i].value=i;
 }
}

Monday, March 26, 2012

Hide Columns in Table

To hide or show table columns, first we get a reference to the table
var table = document.getElementsByTagName("table")[0];
Then we get a reference to the rows collection:
var rows = table.rows;
Let's say we want to hide the first column in the table. We iterate through each row and set the display property of the first element in the cells collection to none.
for(var i=0; i< rows.length; i++){
 rows[i].cells[0].style.display='none';
}
To show a particular column, we would set the display property to blank.
for(var i=0; i< rows.length; i++){
 rows[i].cells[0].style.display='';
}