Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 287
  • Last Modified:

Dont run if first or Last

Im trying to write some code  which when up or down keys are pressed the the previous or next is selected, however if the first element is selected then not to do anything on the up key, and if the last is selected dont do anything on down key.

So what I tried to do is put in an if statment:-
if ($(".selected") != $(".selection").last()) {

Open in new window


However it still doesnt stop.

Ive uploaded my code to JSFiddle.net in the hope an expert can show me where Im going wrong.

The up and down keys should only work when the textbox is selected.
0
tonelm54
Asked:
tonelm54
1 Solution
 
Scott Fell, EE MVEDeveloperCommented:
You could throw a class "first" and "last" and test for that.  Or would you rather loop through each div perhaps $('.selection')each(function(){
0
 
leakim971PluritechnicianCommented:
Use .prev(".selection").length and .next(".selection).length

Test page : http://jsfiddle.net/YRLpx/1/

$(document).ready(function () {
    $("#testBox").keydown(function(event) {
        if (event.which == 40) {
            $("#testConsole").html("Down Pressed");
            $selElement = $(".selected");
            if ($selElement.next(".selection").length) {
                $(".selected").next(".selection").addClass("selected");
                $selElement.removeClass("selected");
                }
            }
        if (event.which == 38) {
            $("#testConsole").html("Up Pressed");
            $selElement = $(".selected");
            if ($selElement.prev(".selection").length) {
                $(".selected").prev(".selection").addClass("selected");
                $selElement.removeClass("selected");                 
                }           
            }        
        if ( event.which == 13 ) {
           event.preventDefault();
          }        
        
        //else {
        //    $("#testConsole").html(event.which);
        //}

        });    
    });
    

Open in new window

0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now