danik
danik

Reputation: 191

Combining change and keyup

I have a form in which I am calculating cost for a product. It depends on both an input value they put in and a select they choose.

Is there a way to combine the change and keyup events into one cleaner segment?

My code is as followed:

https://jsfiddle.net/qrv57qtu/

$('#input').keyup(function(){
    var x = $('#input').val();
    var y = $('#select').val(); 
    if (y == '5') {
        var z = 5;
    }
    else if (y == '10') {
        var z = 10;
    }
    var z = x * y;
    $('#total').html(z);
});

$('#select').change(function(){
    var x = $(this).val();
    var y = $('#input').val();
    if (x == '5') {
        var z = 5;
    }
    else if (x == '10') {
        var z = 10;
    }
    var a = y * z;
    $('#total').html(a);
});

Thank you.

Upvotes: 1

Views: 4781

Answers (2)

Rikin
Rikin

Reputation: 5473

Here's the working code:

 $(document).on("keyup change", "#input, #select", function(){
 var x = $('#select').val();
     var y = $('#input').val();

    if (x == '5') {
                var z = 5;
    }
    else if (x == '10') {
                var z = 10;
    }
    var a = y * z;
    $('#total').html(a);})

https://jsfiddle.net/itsrikin/gaL237qg/

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337743

You can use a single comma-delimited selector to get both elements. Then if you use the on() method you can provide a space-delimited string containing the event names you want to bind to, like this:

$('#input, #select').on('keyup change', function() {
    var x = $('#input').val();
    var y = $('#select').val();

    if (y == '5') {
        var z = 5;
    }
    else if (y == '10') {
        var z = 10;
    }

    var z = x * y;
    $('#total').html(z);
});

Also note that the if condition in your logic is entirely redundant as you overwrite the value of z at the end anyway

Upvotes: 4

Related Questions