0

I want to create a bookmarklet by using javascript, which can retrieve max length of all text box in the page, and then print a table below the page with all id and max length indicated.

Here is my code, however it did not print anything.

javascript: (function() {
  var body =document.getElementsByTagName('body')[0];
    var tbl = document.createElement('table');
  var tbdy = document.createElement('tbody');
    var D = document,
        i, f, j, e;
    for (i = 0; f = D.forms[i]; ++i)
        for (j = 0; e = f[j]; ++j)
            if (e.type == "text") S(e);
    function S(e) {

           var  l= document.getElementById(e.id);
            var x = document.getElementById(e.maxlength);
           var tr=document.createElement('tr');
           var td1=document.createElement('td');
           var td2=document.createElement('td');
           td1.appendChild(document.createTextNode(l));
           td2.appendChild(document.createTextNode(x));
           tr.appendChild(td1);
           tr.appendChild(td2);
          tbdy.appendChild(tr);

    }
  tbl.appendChild(tbdy);
  body.appendChild(tbl);
})

1 Answers1

0

This can actually be done much simpler than you have it.

Working jsfiddle: https://jsfiddle.net/cecu3daf/

You want to grab all of the inputs and run a loop over them. From this you can dynamically create a table and append it to the end of the document.body

var inputs = document.getElementsByTagName("input"); //get all inputs
var appTable = document.createElement("table"); //create a table
var header = appTable.createTHead(); //create the thead for appending rows
for (var i=0; i<inputs.length; i++) { //run a loop over the input elements
  var row = header.insertRow(0); //insert a row to the table
  var cell = row.insertCell(0); //insert a cell into the row
  cell.innerHTML = inputs[i].maxLength; //input data into the cell
  var cell = row.insertCell(0);
  cell.innerHTML = inputs[i].id;
}
document.body.appendChild(appTable); //append the table to the document

To make it a bookmark, simply place the javascript: before hand. There is no need to encase it in a function. You can if you'd like to.

Spencer May
  • 4,266
  • 9
  • 28
  • 48