I'm trying to make calculator(reverse Polish Notation) by using JQuery, HTML, CSS.
I have [0~9 NUMBER BUTTONS] and [+,-,=,/ OPERATOR BUTTONS], and need to make sure these are work differently. But, I want to show them all [input textbox.]
So How can I set each button's Event Handler in Jquery? Any good ideas do you have? Should I use just If, else if, else..?
$(document).ready(function() {
$('button').click(function(){
var showMessage = $(this).attr("value");
console.log(showMessage);
if(showMessage!="Clear"){ // 이어서 붙이기
$('#showProcess').val(function(n,c){
return c+showMessage;
});
}
else if(showMessage=="Clear"){
$('#showProcess').val(""); // Clear
}
});
$('button').hover( // 버튼 hover 시에 음영 설정
function(){
$(this).addClass('active');
},
function(){
$(this).removeClass('active');
}
);
});

It seems like what you've done is created an event handler for selector 'button' (which will select every button on the page), and then you are later checking which button was pressed. Here's an analogy for this. It's like ordering Pepporoni pizza, but the pizza guy comes to your house after cooking every flavor of pizza and later asks you which one you wanted.
The better thing to do would be to select only the exact button(s) for which you want to add a particular event handler. There are many ways to do this, but here's a simple example.
'button.digit' selects every button with a matching class of 'digit'.
<button class="digit" value="5">5</button>
For instance,
$('button.digit').click(function() {
var digitPressed = parseInt($(this).attr('value'));
// perform desired actions
// stack.push(digitPressed);
});
$('button.operand-plus').click(function() {
var opPressed = $(this).attr('value');
// perform desired action for 'Plus' button
// stack.push(opPressed);
});
Of course, you could also use jQuery inline data or read the value of the digit from the innerHTML.
Try this simple example: https://jsfiddle.net/228gp9wc/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With