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 02 Answers
Reset to default 4You 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
版权声明:本文标题:javascript - Combining change and keyup - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745625834a2666964.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论