0

I have already seen this answer, but I want to disable the submitting of the form when pressing enter only for 1 input.

<form>
  <input type="text" name="enterNotDisabled">
  <input type="text" name="enterDisabled">
  <button type="submit">
</form>

For example, I want that when the focus is on the first input, you can submit the form by pressing enter, but this feature would be disabled for the second input.

Thank you for your help.

JacopoStanchi
  • 1,962
  • 5
  • 33
  • 61
  • 2
    Instead of adding the eventListener to the window (as is done in the link), add it to the specific input you don't want to fire the form submit. – WNP Jun 08 '18 at 16:08

2 Answers2

1

just catch the "Enter" key event on that field.

Simple example :

<form>
  <input type="text" name="enterNotDisabled">
  <input type="text" name="enterDisabled" id="input2">
  <button type="submit">
</form>

JS

function catchSubmit(evt) {
  if (evt.code === 'Enter') {
        evt.preventDefault();  
  }
}
document.getElementById('input2').addEventListener('keypress', catchSubmit, false);
ylerjen
  • 4,109
  • 2
  • 25
  • 43
0

Javascript

<form id="form">
  <input type="text" name="enterNotDisabled">
  <input type="text" name="enterDisabled">
  <button type="submit">
</form>

<script type="text/javascript">
    document.querySelector("#form").addEventListener("submit", function(e){
        console.log('event')
        e.preventDefault();
    });

</script>

jQuery

<form id="form">
  <input type="text" name="enterNotDisabled">
  <input type="text" name="enterDisabled">
  <button type="submit">
</form>

<script type="text/javascript">
    $('#form').submit(function(ev) {
        console.log('event')
        ev.preventDefault();
    });

</script>
Omar
  • 2,726
  • 2
  • 32
  • 65