Alexander Hein
Alexander Hein

Reputation: 990

Simplify the similar change event handler on multiple inputs

How can I write this functions more generally. So I don't have to repeat this over and over again?

jQuery("input[name='option1']").change(function () {
    $("#option1").addClass('highlight');
    setTimeout(function () {
        $("#option1").removeClass("highlight");
    }, 100);
});

jQuery("input[name='option2']").change(function () {
    $("#option2").addClass('highlight');
    setTimeout(function () {
        $("#option2").removeClass("highlight");
    }, 100);
});

jQuery("input[name='optionX']").change(function () {
    $("#optionX").addClass('highlight');
    setTimeout(function () {
        $("#optionX").removeClass("highlight");
    }, 100);
});

Upvotes: 0

Views: 54

Answers (2)

Chris
Chris

Reputation: 997

You can try this:

//I would rather use a class instead of just input but anyhow...
$('input').change(function(){
    var elem_name = $(this).attr('name');
    $('#'+elem_name ).addClass('highlight');
    setTimeout(function () {
        $('#'+elem_name).removeClass('highlight');
    }, 100);
});

Upvotes: 0

Tushar
Tushar

Reputation: 87203

You can use attribute starts with selector to bind the event on all the <input> elements whose name starts with option.

// Bind change event on all the `<input>` elements whose `name` attribute starts with `option`.
$('input[name^="option"]').change(function () {
    // Get the `name` of this element
    var name = $(this).attr('name'),
        elem = $('#' + name); // Get the corresponding element whose id is same as the name of this element

    elem.addClass('highlight');
    setTimeout(function () {
        // Use cached element object
        elem.removeClass('highlight');
    }, 100);
});

Upvotes: 2

Related Questions