0

The idea is to change the class of a link to active while removing active from other links and to set a variable to a value depending on the link that is clicked. If "1" is clicked the variable firstNumber would be 1. This is for kind of a "validation" later on. The code is below, the class changing works if the "if else if..." part is removed, so something must be wrong with that part, just what?

$(document).ready(function (){
    $('.numbers-1 a').click(function(){
        $('.numbers-1 a').removeClass('active');
        $(this).addClass('active');

        if ( $(this).hasClass('num-1') ) {
            var firstNumber = 1;
        } else if ( $(this).hasClass('num-2') ) {
            var firstNumber = 2;
        } else if ( $(this).hasClass('num-3') ) {
            var firstNumber = 3;
        } else ( $(this).hasClass('num-4') ) {
            var firstNumber = 4;
        };
    });
});

the html is here

<div class="numbers-1">
    <a class="num-1" href="#">1</a>
    <a class="num-2" href="#">2</a>
    <a class="num-3" href="#">3</a>
    <a class="num-4" href="#">4</a>
</div>

So, why is the if statement not working in the jquery?

1
  • A little tweak suggestion: you don't need this whole block, if you use jquery's $(this.data("myvar") function and data-myvar="1" tags on the elements. Commented Jun 24, 2013 at 8:10

2 Answers 2

2

else was supposed to be an else if on your final statement I'm assuming as else doesn't take a conditional statement.

else if ( $(this).hasClass('num-4') ) {
   var firstNumber = 4;
}

jsFiddle here.

Sign up to request clarification or add additional context in comments.

1 Comment

Well that was simple... Thanks! Come up with a simple way to check the selected numbers?
0

Just tried to simplify your code. What about this ?

$(document).ready(function (){
    $('.numbers-1 a').click(function(){
        $('.numbers-1 a').removeClass('active');

        var currentClass = $(this).attr('class');

        $(this).addClass('active');

        var firstNumber = parseInt(currentClass.split('-')[1]);
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.