0

I've had a problem with my code for a few hours now. When you press the button its activates the function, but when I call the function with onkeypress it tells me it is not defined.

I've already tried to put it in a normal function if you can say, I've tried to put it in global with window.myfunction = myfunction

    <div> 
    <input onkeypress="if(event.keyCode==13){test();}" id="number" type="text" placeholder="Tapez un nombre pour commencer">
    <input type="button" value="Envoyer" class="btn">
<div>

$(function(){
    $(".btn").click(function click(){
        // reste du code
    });

})

I would like the same action to be done when you press the enter key as when you press the button (activate the click function)

Kiwi
  • 44
  • 5

1 Answers1

0

What I recommend in this case is switching to a form and handling the submit event. That way, not only can the form be submitted by the button, by pressing enter, but also by screen readers and other devices which understand forms.

Try something like this instead:

<form>
    <input name="number" type="text" placeholder="Tapez un nombre pour commencer">
    <input type="submit" value="Envoyer" class="btn">
</form>

Then in your JavaScript:

$(function() {
  $('form').on('submit', function(e) {
    e.preventDefault(); // Make sure the form doesn't actually submit
    console.log(new FormData(e.target));
  });
});

Also, for more information on FormData, see my answer here: https://stackoverflow.com/a/46376650/362536

Brad
  • 159,648
  • 54
  • 349
  • 530
  • the submit updates the page, I made sure that the page does not refresh otherwise my function does not work anymore and it is possible to do it without the submit ? – Kiwi Aug 08 '19 at 17:41
  • @Doss Make sure `e.preventDefault()` is running. Is the form submit handler even attaching? Yes, of course it's possible to do it otherwise but it's easier/better to handle things the standard way. – Brad Aug 08 '19 at 17:42
  • I didn't put a
    – Kiwi Aug 08 '19 at 18:59
  • I'm a beginner, sorry. – Kiwi Aug 08 '19 at 19:20
  • @Doss No problem! Happy to help. – Brad Aug 08 '19 at 19:29