Prithvi514
Prithvi514

Reputation: 163

Reading data from text boxes inside a table

I have the following two function in my code, the addValueToSTorage has to read the editable table data and add the values to the localStorage and the populate table reads the values from localStorage and populates the table with the updated values and makes the table non-editable.

function addValueToStorage() {
    localStorage.clear();
    var table = document.getElementById('table');
    var i;
    var j;
    var rowLength = table.rows.length;
    for (i = 0; i < rowLength; i++) {
        var value=[];
        for (j = 0; j < 4; j++) {
            value.push(table.rows[i].cells[j].firstChild.data);
        }
        var val=JSON.stringify(value);
        var key = "xyz" + localStorage.length;
        localStorage.setItem(key, val);
    }
    populatetable();
}

function populatetable() {
    $('#table').empty();
    var header = "<tr><th>Select</th><th>Name</th><th>1</th><th>2</th><th>3</th></tr>";
    $('#table').append(header);
    for (var i = 0; i < localStorage.length; i++) {
        var key = localStorage.key(i);
        if (key.substring(0, 5) == "xyz") {
            var value = JSON.parse(localStorage.getItem(key));
            var xyzvalue = "<tr><td><input type=\"checkbox\" value=" + key + "></td><td><input type=\"text\"  value=" + value[0] + "></td><td><input type=\"text\"  value=" + value[1] + "</td><td><input type=\"text\"  value=" + value[2] + "</td><td><input type=\"text\"  value=" + value[3] + "</td></tr>";
            $('#table').append(xyzvalue);
        }
    }
    $('#table:input').prop("disabled", true);
}

The addValueToStorage is able to read data from the cells of a normal table, but since my table is editable I have used textboxes inside the table and the addValueToStorage is not able to read the data from the cells and also the table size is completely distorted and is overflowing the div enclosing it because of the textboxes. Any help on extracting the data and setting the size of the table is greatly appreciated. Thanks in Advance

Upvotes: 0

Views: 418

Answers (1)

thelastshadow
thelastshadow

Reputation: 3644

try changing:

for (i = 0; i < rowLength; i++) {
    var value=[];
    for (j = 0; j < 4; j++) {
        value.push(table.rows[i].cells[j].firstChild.data);
    }
    var val=JSON.stringify(value);
    var key = "xyz" + localStorage.length;
    localStorage.setItem(key, val);
}

to

for (i = 0; i < rowLength; i++) {
    var value=[];
    for (j = 0; j < 4; j++) {
        // getAttribute is probably what you're after here
        value.push(table.rows[i].cells[j].firstChild.getAttribute('value'));
    }
    var val=JSON.stringify(value);
    var key = "xyz" + localStorage.length;
    localStorage.setItem(key, val);
}

Upvotes: 2

Related Questions