Select element with same class and other class

56 Views Asked by At

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?

1

There are 1 best solutions below

0
On

I would suggest to put every row to the separate container (if you didn't do it yet) like this

<div>
    Total:     <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 />
</div>
<div>
    Total:     <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 />
</div>

and in this case you can use the next script

$(document).ready(function() {
    $(".herd_weight, .herd_buy").on('keyup', function() {
        var numAnimals = $("[name='herd_num_begin']").val();

        if( $(this).is('.total') ) {
            $('.peranimal', $(this).parent()).css({
                'background-color': 'yellow'
            })
        }
        else if( $(this).is('.peranimal') ) {
            $('.total', $(this).parent()).css({
                'background-color': 'yellow'
            })
        }
    });
});

JS fiddle example here