Andreas C
Andreas C

Reputation: 183

Hitting enter refreshes the page jQuery

I have written some code to create a to-do list using jQuery. If I hit enter it should submit the input into a list down below but the problem is that the page refreshes as if it's submitting a form. I've checked out multiple threads on SO in regards to this but I have found no solution.

Stop reloading page with 'Enter Key'

Prevent users from submitting a form by hitting Enter

I have tried to add e.preventDefault(); and return: false; which stops the refresh but also prevents the adding to the list upon hitting enter.

I have tried the following in the html form tag:

onSubmit="return false;"

<form ... onkeydown="return event.key != 'Enter';">

action="#"

Is there something wrong with my IIFE that's causing this?

let checklist = (function() {
  function newItem() {

    let li = $('<li></li>');
    let inputValue = $('#input').val();
    let input = $('#input');
    let deleteIcon = $('<div></div>');

    function crossOut() {
      li.toggleClass('strike');
    }

    function deleteListItem() {
      li.addClass('delete');
    }

    if (inputValue === '') {
      alert('You must write something!');
    } else {
      $('#list').append(li);
      input.val('')
    }
    
    deleteIcon.append(document.createTextNode('X'));
    li.append(deleteIcon);
    li.append(inputValue);
    
    deleteIcon.on('click', deleteListItem);
    li.on('dblclick', crossOut);

    $('#list').sortable();
  }
  
  return {
    newItemf: newItem
  };

})();

$('#button').on('click', checklist.newItemf)

$(window).on('keypress', function (e){
  if(e.which == 13) {
    checklist.newItemf;
    return false;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="toDoList">
        <input type="text" name="ListItem" id="input">
      </form>

      <div id="button">Add</div>
      <br/>
      <ol id="list"></ol>

Upvotes: 1

Views: 64

Answers (2)

Andreas C
Andreas C

Reputation: 183

I found the solution but I don't fully understand why I don't need a return false;

Maybe it's that I am trying to submit the input when "enter" is keyed down instead of preventing all inputs. Thank you @isick as your answer pointed me in the right direction!

This is the code that was needed!

$('form').on('submit', checklist.newItemf)

Upvotes: 0

isick
isick

Reputation: 1487

The easiest way to stop this is to catch the onSubmit event and just return false. I believe the following should be sufficient:

$('form').on('submit', function(e) {
    e.preventDefault();
    return false;
});

Upvotes: 1

Related Questions