Kirk Ross
Kirk Ross

Reputation: 7163

Simply / condense this code?

I often find myself writing two blocks of code — one for the init and the same for on change, like below. Suggestions for a more condensed / elegant approach?

$( '.some-class' ).each(function(){
    var title = $(this).children('option:selected').text();
    $( this ).attr('title', title);
});
$( '.some-class' ).change(function(){
    var title = $(this).children('option:selected').text();
    $( this ).attr('title', title);
});

Upvotes: 0

Views: 25

Answers (1)

jonny
jonny

Reputation: 3098

function doSomething (){
    var title = $(this).children('option:selected').text();
    $( this ).attr('title', title);
}

$( '.some-class' ).each(doSomething);
$( '.some-class' ).change(doSomething);

Perhaps?

Upvotes: 2

Related Questions