Button function in svelte

I just changed a few things in my code... in this one I want the button 'ENTER' to function as SAME as the input field above but don't know why is it not working:

THIS BUTTON CODE:

 <div class="buttonDate">
    <button on:click={newTodoTitle}>Enter</button>
</div>

https://svelte.dev/repl/f137b909d3e740f99a030576189091db?version=3.22.3

1 answer

  • answered 2020-05-22 14:39 Matt Wolff

    In your Todos.svelte template, newTodoTitle is only a string. on:click={newTodoTitle} should instead call a function. In particular, it sounds like it should call your addTodo function. Unfortunately, addTodo has a check in place for the enter key. With a few adjustments, you should be able to get it working.

    1. Create a new function called submit for your keydown:
    function submit(event) {
      if (event.key === 'Enter') {
        addTodo();
      }
    }
    
    1. Have that function call a modified version of addTodo:
    function addTodo() {
      todos = [...todos, {
        id: nextId,
        completed: false,
        title: newTodoTitle,
        date: toDoItemDate,
      }];
      nextId = nextId + 1;
      newTodoTitle = '';
      toDoItemDate = '';
    }
    
    1. Call Submit from your input
    <input 
      type="text" 
      class="todo-input" 
      placeholder="click a to-do, select target date, and hit enter..." 
      bind:value={newTodoTitle} 
      on:keydown={submit}>
    
    1. Call addTodo from your button click
    <button on:click={addTodo}>Enter</button>
    

    Here it is in a REPL