Question

jsfiddle.net file

$(document).ready($(function change_cell_content() {
            $("td").on("click",
                function(){
                    var $cell_id_ref = $(this).attr('cellID');
                    var $table_id_ref = $(this).parent().parent().parent().attr('tableID');
                    var newValue;

                    var currentValue = document.querySelector('[cellID="' + $cell_id_ref + '"]').innerHTML;
                    alert(currentValue);

                    var changeValue = prompt("Enter a new value. (Current " + currentValue + ")");
                    if ( changeValue!==null ) {
                        newValue = changeValue;
                        document.querySelector('[cellID="' + $cell_id_ref + '"]').innerHTML = newValue;
                    }
                });
        }));

The first table works perfectly, the other three do not.

Click on any cell. An alert will show the tableID of what you clicked on. A prompt will popup and ask for a new value(stating a current value in the prompt). This is the problem, the currentValue variable is only getting from the first table even though I am using cellID($cell_id_ref) and tableID($table_id_ref) to attempt to direct it to other tables.

Any help or comments would be appreciated.

Was it helpful?

Solution

You can simplify your code and make use of jQuery instead of querySelectorAll:

$(function change_cell_content() {
    $("td").on("click", function () {

        var cell_id_ref = $(this).attr('cellID');
        var $table = $(this).closest('table');
        var newValue;

        var currentValue = $(this).html();
        alert(currentValue);

        var changeValue = prompt("Enter a new value. (Current " + currentValue + ")");
        if (changeValue !== null) {
            $table.find('[cellID="' + cell_id_ref + '"]').text(changeValue);
        }
    });
});

You problem was in this line:

document.querySelector('[cellID="' + $cell_id_ref + '"]').innerHTML = ...

You should select a cell in current table, however above code always selects the first cell from the first table.

Demo: http://jsfiddle.net/waH5S/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top