Consider this HTML:
Totaal: <input type="text" class="herd_buy total" name="herd_buy_total" /><br />
Per animal: <input type="text" class="herd_buy peranimal" name="herd_buy_per_animal" /><br />
If the user fills in the total, it should calculate the per animal price, and the other way around.
The script should be dynamic, since I have more rows with total/per animal properties.
So I started a function. I figured that I use the class, and if the selected element has the class total
, I select the peranimal
class. But I got stuck...
$(".herd_weight, .herd_buy").on('keyup', function() {
var numAnimals = $("[name=herd_num_begin]").val();
if( $(this).hasClass('total') ) {
var s = $(this).attr('class');
$( "."+s+".peranimal" ).not(this).css('background-color', 'yellow');
}
else if( $(this).hasClass('peranimal') ) {
var s = $(this).attr('class');
$( "."+s+".total" ).not(this).css('background-color', 'yellow');
}
});
I figured that $(this).attr('class')
gives me herd_buy total
, so that makes my selector .herd_buy total .peranimal
... which obviously is wrong.
How can I select the right element?
I would suggest to put every row to the separate container (if you didn't do it yet) like this
and in this case you can use the next script
JS fiddle example here