Reputation: 2449
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
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
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:
$('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
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);
});
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);
});
Upvotes: 8