You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

待办App开发:输入为空时如何不生成Delete按钮?

Fix for Blank Task Creation in To-Do App

Hey there! I see the issue here—you're calling addTask() before checking if the task input is empty. That's why even when you submit a blank value, the empty task item with a Delete button gets created first, and then the alert pops up. Let's fix that by reordering your logic.

Modified JavaScript Code

window.addEventListener('load', () => {
  const taskForm = document.querySelector('#task-form');
  const taskInput = document.querySelector('#task-input');
  const taskList = document.querySelector('#task-list');

  taskForm.addEventListener('submit', (e) => {
    e.preventDefault();

    const task = taskInput.value.trim(); // Add trim() to handle whitespace-only inputs

    // First check if task is empty
    if (!task) {
      alert('Please add a task.');
      return; // Exit the function early if no task
    }

    // Only proceed to add task if input is valid
    addTask(task);
    taskInput.value = ''; // Clear input after successful task addition
  });

  // Add button
  const addTask = (task) => {
    const divItem = document.createElement('div');
    const showItem = taskList.appendChild(divItem);
    showItem.innerHTML = task;

    // Delete button
    const buttonDelete = document.createElement('button');
    buttonDelete.innerHTML = 'Delete';
    divItem.appendChild(buttonDelete);

    buttonDelete.addEventListener('click', (e) => {
      e.preventDefault();
      deleteTask(buttonDelete);
    });
  };

  const deleteTask = (buttonDelete) => {
    const selectTask = buttonDelete.closest('div');
    taskList.removeChild(selectTask);
  };
});

Key Changes Made:

  • Reordered the validation check: Now we first check if the task is empty (using trim() to also catch inputs with only spaces) before calling addTask(). If the input is invalid, we show the alert and exit the function immediately, so no empty task is created.
  • Moved input clearing: We only clear the input field after we've confirmed the task is valid and added it to the list. This is a small UX improvement—if the user accidentally submits a blank, their input (if any) stays in the field instead of getting cleared.

HTML Code (Unchanged)

<form id="task-form">
  <input id="task-input" type="text" placeholder="What's your plans?" />
  <input id="task-submit" type="submit" value="Push" />
</form>

<div>
  <h1>Tasks</h1>
  <div id="task-list"></div>
</div>

Now when you submit a blank or whitespace-only input, you'll only see the alert, and no empty task item will be added to the list.

内容的提问来源于stack exchange,提问作者user19816368

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:15:36