Dan Jimenez
Dan Jimenez

Reputation: 115

Refactoring help needed

The following example works fine, but I wanted to see if there was a way I can refactor the code further and not have to add a click event handler for every subsequent question/answer set I could potentially add to the page.

So instead of having to add another "click" event handler, with script being repeated:

$(document).ready(function () {
    $('.answer1.option').click(function () {
        $(this).removeClass('not-selected');
        $('.answer1.option').not(this).addClass('not-selected');
    });
    $('.answer2.option').click(function () {
        $(this).removeClass('not-selected');
        $('.answer2.option').not(this).addClass('not-selected');
    });
});

The code would just use a single click eventhandler and use that for any subsequent question/answer sets.

Id want to find an answer that maybe takes a variable of some sort and use that to iterate through the options. Any ideas?

Here is a JSfiddle to visually explain what I mean and the functionality I'm ultimately looking for:

http://jsfiddle.net/Rq4rp/

Upvotes: 0

Views: 61

Answers (2)

Drew Dahlman
Drew Dahlman

Reputation: 4972

You could condense this quite a bit. By using this and siblings.

$(document).ready(function () {
    $('.option').click(function () {
        $(this).removeClass('not-selected');
        $(this).siblings().addClass('not-selected');
    });
});

This will work in siblings again and you would never need to actually specify the specific answer.

http://jsfiddle.net/Rq4rp/3/

As pointed out by @YuryTarabanko you could condense this even more -

$(document).ready(function () {
    $('.option').click(function () {
        var cls = "not-selected"
        $(this).removeClass(cls).siblings().addClass(cls);
    });
});

http://jsfiddle.net/Rq4rp/5/

Upvotes: 6

Adjit
Adjit

Reputation: 10305

Here is what I would do...you put all of your options into <div class="answerContainer">...</div>

and use this code to execute:

$(document).on('click', '.answerContainer .option', function(){
    $(this).removeClass('not-selected');
    $(this).siblings().addClass('not-selected');
});

Example fiddle: http://jsfiddle.net/Rq4rp/4/

Upvotes: 0

Related Questions