简体   繁体   中英

Using the Up and Down arrows keys to scroll (highlight) row in an HTML table

I can't seem to be able to use my arrow Up and Down keys on the keyboard to be able to navigate (highlight row) in my HTML table. It should be noted that once a row is clicked and I hit the up or down arrow keys, the highlighted row should move accordingly.

What am I doing wrong?

Here is the HTML markup:

<!DOCTYPE html>

<html>

<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

<style type="text/css">

.highlight {

    background-color: rgb(255,0,0);

}

</style>

<script type="text/javascript">

window.onload = function() {

var rowCount = $('#data >tbody >tr').length;
$("#maxrows").val(rowCount);

    var $tbody = $("#data tbody").on('click', 'tr', function() {
            highlight($(this));
    });


    $('#goto_first').click(function() {
        var $first = $tbody.find('tr').first();
            highlight($first);
    });

    $('#goto_prev').click(function() {
        var $prev = $tbody.find('.highlight').prev();
            highlight($prev);
    });


    $('#goto_next').click(function() {
        var $next = $tbody.find('.highlight').next();
            highlight($next);
    });

    $('#goto_last').click(function() {
        var $last = $tbody.find('tr').last();
            highlight($last);
    });

    $('#goto_row').click(function() {

        var $row = prompt("Enter row number")

        highlight($("#data tr").eq($row));

    });

    $('#remove_row').click(function() {

        var $row = $tbody.find('.highlight')

        $row.remove();

        renumberRows()

    });


    $('#data tr').keydown(function (e) {

        if (e.which == 40) {//down arrow
            var $row = $tbody.find('.highlight')

            highlight($row);
        }

          else if (e.which == 38) {//up arrow
            var $row = $tbody.find('.highlight')

            highlight($row);
        }

     });

    function highlight($row) {
            if ($row.length) {
                $tbody.children().removeClass("highlight");
                $row.addClass('highlight');
                $("#rownum").val($row[0].rowIndex);
            }
    }

    function renumberRows() {
        $('#data tr').each(function(index, el){
            $(this).children('td').first().text(index++);
        });
    }

}
</script>

</head>

<body>

<table id="data" border="1" cellspacing="1" cellpadding="1">

    <thead>
        <tr>
            <th>#</th>
            <th>header2</th>
            <th>header3</th>
            <th>header4</th>
            <th>header5</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
        </tr>
        <tr>
            <td>2</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
        </tr>
        <tr>
            <td>3</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
        </tr>
        <tr>
            <td>4</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
        </tr>
        <tr>
            <td>5</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
        </tr>
        <tr>
            <td>6</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
            <td>data</td>
        </tr>
    </tbody>
</table>
Row Number:
<br>
<input type="text" id="rownum" readonly><br>
of
<br>
<input type="text" id="maxrows" readonly>
<br>
<input type="button" id="goto_first" value="first">
<input type="button" id="goto_prev" value="prev">
<input type="button" id="goto_next" value="next">
<input type="button" id="goto_last" value="last">
<input type="button" id="goto_row" value="goto row">
<input type="button" id="remove_row" value="remove row">

</body>
</html> 

I'd change it up a bit. First define two functions for next and previous.

function gotoNext(){
    var $next = $tbody.find('.highlight').next();
        highlight($next);
}

function gotoPrevious () {
    var $prev = $tbody.find('.highlight').prev();
        highlight($prev);
}

Then, use them in your existing click handlers.

$('#goto_prev').click(gotoPrevious);

$('#goto_next').click(gotoNext);

And use them in your keydown handlers, which need to be attached to the document:

$(document).keydown(function (e) {

  if ( $tbody.find('.highlight').length ) {

    if (e.which == 40) {//down arrow
        gotoNext();
    }

    else if (e.which == 38) {//up arrow
        gotoPrevious();
    }
 }

 });

Note that I added a check to make sure something was highlighted already in the table to ensure you're not capturing normal up/down scrolling.

Here's a Codepen example .

JSfiddle

This is the function for the keydown event. I also made a simple function to highlight TRs. Take a look.

This system is different from yours. I'm just showing you another way to do that.

I decided to use .index() to determinate the positioning. I find this quite useful and rapid.

$(document).keydown(function (e) {

  switch(e.which) 
  {
       case 38:
           $('#goto_prev').trigger('click');
           break;
       case 40:
           $('#goto_next').trigger('click');
           break;
   }

});

Don't Repeat yourself. Use a function. Keep it simple

function highlight(tableIndex) {
    // Just a simple check. If .highlight has reached the last, start again
    if( (tableIndex+1) > $('#data tbody tr').length )
        tableIndex = 0;

    // Element exists?
    if($('#data tbody tr:eq('+tableIndex+')').length > 0)
    {
        // Remove other highlights
        $('#data tbody tr').removeClass('highlight');

        // Highlight your target
        $('#data tbody tr:eq('+tableIndex+')').addClass('highlight');
    }
}

In this example, both keyboard keys and buttons works. I also made a check which allows you to start over if you reach the end of the table.

This should suit your needs. It'll be also quite useful to anyone else who's looking for a really simple method. I so suggest you to improve it. Adapt it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM