admin管理员组

文章数量:1435859

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 bine the change and keyup events into one cleaner segment?

My code is as followed:

/

$('#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.

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 bine the change and keyup events into one cleaner segment?

My code is as followed:

https://jsfiddle/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.

Share Improve this question edited Jul 12, 2016 at 15:27 Mohammad 21.5k16 gold badges57 silver badges85 bronze badges asked Jul 12, 2016 at 15:24 danikdanik 1913 silver badges14 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

You can use a single ma-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

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/itsrikin/gaL237qg/

本文标签: javascriptCombining change and keyupStack Overflow