Apply jquery code to multiple text areas

I have code that works, 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 elements into some kind of array, so that I can use the same code for several different fields.

+2
javascript jquery
Jul 10 '13 at 14:27
source share
3 answers

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

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

Fiddle

EDIT:

as noted above, if 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

+8
Jul 10 '13 at 14:30
source share

This can be done using the class name:

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

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

Fiddle

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

The class name is not very suitable for defining a relationship. Think about whether any constructor is provided to your code and if it runs extra classes for styling, this will break the code.

+2
Jul 10 '13 at 2:31 on
source share

Try below

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

check out jsfiddle

After checking @ I creaked, I realized my mistake. If you add a class to input , then the above will not lead to the fact that it will accept the entire attribute.

As suggested by adeneo, try using HTML5 data attributes .

I'hv update it fiddle .

+1
Jul 10 '13 at 14:35
source share



All Articles