+ 3
💙 One question about JAVASCRIPT 💙
How can I do this: I have a button that name of it is "btnequal". <input name"btnequal" type="button" onclick="answer()" /> I want to that if a person press "=" key on keyboard this button executes answer() function. I want to do this job for my engineering calculator project. if you want to see my code check this link. https://code.sololearn.com/WQ64sRWc8iXw/?ref=app
6 Answers
+ 3
.keyCode is used to determine which key is pressed. e.g.:
<script type="text/javascript">
function myKeyPress(e) {
var keynum;
if(window.event) {
keynum = e.keyCode; }
else if(e.which) {
keynum = e.which; } alert(String.fromCharCode(keynum)); } </script> <form> <input type="text" onkeypress="return myKeyPress(event)" /> </form>
that displays on screen what the key pressed by the user was. in your case, you want an "onkeypress" instead of an "onclick" in your input type. declare a var as user input, then add an if statement to complete it.
if (input variable name).keyCode = "="
{ code here; }
+ 5
Isn't it okay already? I mean, it works!
+ 2
Below is example code for you. Note, you can set up checks for ALL of your calculator buttons so you can use numpad or whatever you want for it instead of having to click them.
Hope this helps.
@Pegasus If it ain't broken, don't fix it. If it can be better, it's as good as broken. ;)
JQUERY:
<script>
$( "#myInputBox" ).keypress(function( event ) {
if ( event.which == 13 || event.which == 187) {
event.preventDefault();
// Do your calculations or whatever here
}
});
$( "#myEqualsButton" ).click(function() {
$( "#myInputBox" ).keypress();
});
</script>
KEYCODES:
https://css-tricks.com/snippets/javascript/javascript-keycodes/
+ 2
The ASCII HTML code of
=
is the following
=
+ 1
@Pegasus In his current version, it doesn't allow keyboard input, so you can't use your numpad on your keyboard to operate it as you would expect any calculator to operate on a computer. It's 100% mouse-clicking at the moment, which isn't ideal for any calculator program that's on a computer unless it's intended for mobile situations only.
Besides, considering that he posted a very specific question on how to do something particular, that's a pretty lame answer to give. "What? You want to do something you wanted to do? Something that's expected from calculators? Why would you do that? Code already minimally works and I don't have the answer you're seeking. Move on, it works!"
+ 1
thanks a lot friends, your comments really help me