0

How to catch space bar input from input type like this:

<html>
<head>
<script type = "text/javascript">
function  lala(aa){
    console.log(aa + " dasda");
}
</script>
</head>
<body>
<input type = "number" value =  "0.00" class = "no-spin" onchange='lala(this)' />
</body>
</html>

onchange does not trigger the space bar input. I would like to change the value to 0 again when space bar is pressed.

Dekso
  • 541
  • 4
  • 23

3 Answers3

0

The change event is only fired when the input looses focus, not on each keystroke.

The input event does, for any valid input (and space isn't one in this case).

You can use keyup and then do your thing:

<input type="number" value="0.00" class="no-spin" onkeyup="lala(event, this)" />

You can check aa.keyCode == 32 (aa being your "lala" argument name) to know if the key pressed was the spacebar, and then do your thing.

Something like this if you want this to happen when the value is empty:

function lala(event, input) {
    if (event.keyCode == 32 && !input.value) {
        input.value = '0.00';
    }
}
kLabz
  • 1,837
  • 1
  • 14
  • 14
0

Do you want something like this ?

  1. I change type to text from number to allow space
  2. I remove onchange event and created addEventListener to watch keyup
  3. Instead value you should keep 0.00 in placeholder to make better user friendly.

document.body.addEventListener("keyup", function(e){
    if(e.keyCode == 32){
        document.querySelector("#test").value = '';
    }
});
<input type="text" placeholder="0.00" value="" class="no-spin" id="test" />
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
0

Use keyup event to catch every change to the input field (you'll need to give the input field an id):

document.getElementById('input-id').addEventListener('keyup', function(e) {
  // everything will be available here
});

you shouldn't declare javascript events as html attributes. it's bad practice

George
  • 1,706
  • 1
  • 11
  • 12
  • 1
    +1 for the html attribute, event if it is easier to share code like this. But the input event won't be fired for the spacebar on an input number. – kLabz Jan 05 '18 at 11:46
  • thanks @kLabz I've updated the answer – George Jan 05 '18 at 11:49