Chamithra Thenuwara
Chamithra Thenuwara

Reputation: 419

How to get whether the pressed key is backspace or not in JavaScript?

I have a input text which used to filter data in a table using the onkeyup event

<input id="NameFilterText" type="text" onkeyup="return filterDataRow('NameFilterText','Name'); return false;" /></td>

I'm calling this JavaScript function in the onkeyup to the filter data

function filterDataRow(field, name) {
    var textBox = document.getElementById(field);
    var columnName = name;
    var table = document.getElementById('table1');
    var headRow = table.rows[0];
    var column = 0
    var text = textBox.value;

    for (var i = 0; i < headRow.cells.length; i++) {
        var cellName = headRow.cells[i].innerHTML;
        if (cellName == columnName) {
            column = i;
            break;
        }
    }

    for (var i = 1; i < table.rows.length; i++) {

        table.rows[i].style.display = 'table-row'; // execute only when pressing backspace

        for (var v = 0; v < text.length; v++) {
            var CurCell = table.rows[i].cells[column];
            var CurCont = CurCell.innerHTML.replace(/<[^>]+>/g, "");
            var reg = new RegExp(text + ".*", "i");

            if (CurCont.match(reg) == null) {
                table.rows[i].style.display = 'none';
            }
        }
    }
    return false;
}

I don't want to execute that commented line if the pressed key is not backspace. How can I do that ?

Upvotes: 1

Views: 161

Answers (3)

B T
B T

Reputation: 60993

I wrote a library called keysight that does this kind of thing for all keyboard keys:

node.addEventListener("keydown", function(event) {
    var key = keysight(event).key
    if(key === '\b') {
      console.log("We got one!")
    }
})

Upvotes: 0

Marco Bonelli
Marco Bonelli

Reputation: 69477

First you need to change the onkeyup event to this:

<input ... onkeyup="filterDataRow('NameFilterText','Name');" />

Then inside the function edit the line you want to be executed only one time adding this if-statement:

if (window.event.keyCode == 8) table.rows[i].style.display = 'table-row';

Upvotes: 0

Ayush Ghosh
Ayush Ghosh

Reputation: 487

var input = document.getElementById('NameFilterText');
var keydown=0;
input.onkeydown = function() {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 )
        keydown=1;
    return false;
};

Now in your code filterDataRow()

if(keydown=1){  do your thing. and set keydown = 0 again}

Hope it Helps !

Upvotes: 1

Related Questions