J.Zil
J.Zil

Reputation: 2449

Apply jquery code to multiple textareas

I have some code which is working but I have a lot of duplication: http://jsfiddle.net/6Wp2j/25/

$('input.apple').on('keyup', function() {
    $("div.apple").html(this.value);
});

$('input.orange').on('keyup', function() {
    $("div.orange").html(this.value);
});

$('input.banana').on('keyup', function() {
    $("div.banana").html(this.value);
});

I was wondering if there is a way to put the items into some sort of array, so that I can have the same code apply to several different fields.

Upvotes: 2

Views: 3487

Answers (3)

Praveen
Praveen

Reputation: 56539

Try below

$('input').on('keyup', function () {
    var clas = $(this).prop('class');
    $("div." + clas).html(this.value);
});

check this JSFiddle

After checking @Ian's fiddle, I understood my mistake. Incase if you add class to the input then the above will fail beacuse it takes the whole attribute.

As adeneo suggested, try to use HTML5 data attributes.

I'hv update it fiddle.

Upvotes: 1

MrCode
MrCode

Reputation: 64536

It can be done using the class name:

$('input').on('keyup', function() {
    $("div." + $(this).attr('class')).html(this.value);
});

I would prefer to have the relationship/link in a data-fruit attribute, for example:

Fiddle

$('input').on('keyup', function() {
    $("div[data-fruit=" + $(this).data('fruit') + "]").html(this.value);
});

The class name is not really best suited to define the relationship. Consider if some designer is given your code, and starts throwing extra classes in there for styling, this would break the code.

Upvotes: 2

adeneo
adeneo

Reputation: 318342

You can target all inputs, or just give them a common class to target, and extract something, I used the class, but data attributes would be easier if the elements had multiple classes etc :

$('input').on('keyup', function() {
    $('.'+this.className).html(this.value);
});

FIDDLE

EDIT:

as noted above, if the elements have multiple classes, use data attributes :

<input class="input" data-id="apple" >
<input class="input" data-id="orange" >
<input class="input" data-id="banana" >  

JS

$('.input').on('keyup', function() {
    $('.' + $(this).data('id')).html(this.value);
});

FIDDLE

Upvotes: 8

Related Questions