Кнопка Отключить после добавления задачи в список задач - PullRequest
0 голосов
/ 10 ноября 2018

Я хотел бы добавлять некоторые элементы в список задач и отключать кнопку каждый раз. Когда страница загружается, все работает нормально.

Я бы также хотел отключить кнопку после добавления каждой задачи.

Если добавить новое задание и нажать кнопку «Отправить», оно будет работать нормально. Но если пользователь выбирает нажатие кнопки «Ввод» вместо отправки, он становится активным.

Что нужно сделать, чтобы отключить кнопку отправки, если пользователь предпочитает кнопку «Ввод» вместо кнопки «Отправить»?

<!DOCTYPE html>
<html>
    <head>
        <script>
            document.addEventListener('DOMContentLoaded', () => {

                // By default, submit button is disabled
                document.querySelector('#submit').disabled = true;

                // Enable button only if there is text in the input field
                document.querySelector('#task').onkeyup = () => {
                    document.querySelector('#submit').disabled = false;
                };

                document.querySelector('#new-task').onsubmit = () => {

                    // Create new item for list
                    const li = document.createElement('li');
                    li.innerHTML = document.querySelector('#task').value;

                    // Add new item to task list
                    document.querySelector('#tasks').append(li);

                    // Clear input field and disable button again
                    document.querySelector('#task').value = '';
                    document.querySelector('#submit').disabled = true;

                    // Stop form from submitting
                    return false;
                };

            });
        </script>
        <title>Tasks</title>
    </head>

Часть тела html.

    <body>
        <h1>Tasks</h1>
        <ul id="tasks">
        </ul>
        <form id="new-task">
            <input id="task" autocomplete="off" autofocus placeholder="New Task" type="text">
            <input id="submit" type="submit">
        </form>
    </body>
</html>

Ответы [ 3 ]

0 голосов
/ 10 ноября 2018

Когда вы нажимаете клавишу enter, список событий keyup срабатывает. Вы должны поставить здесь кнопку включения в условиях

 document.querySelector('#task').onkeyup = (e) => {
                   if(e.which === 13){
                     return; // When user enter key press  
                   }
                    document.querySelector('#submit').disabled = false;
                };
0 голосов
/ 11 ноября 2018

Я смотрел курс веб-программирования Harvard CS50 и хотел бы поделиться другим решением. Это не часть домашней работы, задания и т. Д., Поэтому я не стесняюсь делиться решением.

В основном мы включаем кнопку, если в поле ввода есть текст.

// Enable button only if there is text in the input field
document.querySelector('#task').onkeyup = () => {
    if (document.querySelector('#task').value.length > 0)
        document.querySelector('#submit').disabled = false;
    else
        document.querySelector('#submit').disabled = true;
};

// By default, submit button is disabled
document.querySelector('#submit').disabled = true;

// Enable button only if there is text in the input field
document.querySelector('#task').onkeyup = () => {
    if (document.querySelector('#task').value.length > 0)
        document.querySelector('#submit').disabled = false;
    else
        document.querySelector('#submit').disabled = true;
};

document.querySelector('#new-task').onsubmit = () => {

    // Create new item for list
    const li = document.createElement('li');
    li.innerHTML = document.querySelector('#task').value;

    // Add new item to task list
    document.querySelector('#tasks').append(li);

    // Clear input field and disable button again
    document.querySelector('#task').value = '';
    document.querySelector('#submit').disabled = true;

    // Stop form from submitting
    return false;
};
#submit:disabled {
  opacity: 0.5;
}
<h1>Tasks</h1>
<ul id="tasks">
</ul>
<form id="new-task">
    <input id="task" autocomplete="off" autofocus placeholder="New Task" type="text">
    <input id="submit" type="submit">
</form>
0 голосов
/ 10 ноября 2018

Когда вы нажимаете кнопку enter, ваш обработчик событий onkeyup меняет отключенное состояние кнопки отправки на false, и ввод работает.

Вместо этого прослушайте событие input поля #task и включите / отключите кнопку отправки в соответствии с изменениями содержимого. Это также будет обрабатывать случай, когда отправка включена после удаления текста.

// Enable button only if there is text in the input field
document.querySelector('#task').addEventListener('input', (e) => {
  document.querySelector('#submit').disabled = e.target.value === '';
});

Пример:

// By default, submit button is disabled
document.querySelector('#submit').disabled = true;

// Enable button only if there is text in the input field
document.querySelector('#task').addEventListener('input', (e) => {
  document.querySelector('#submit').disabled = e.target.value === '';
});

document.querySelector('#new-task').onsubmit = () => {

  // Create new item for list
  const li = document.createElement('li');
  li.innerHTML = document.querySelector('#task').value;

  // Add new item to task list
  document.querySelector('#tasks').append(li);

  // Clear input field and disable button again
  document.querySelector('#task').value = '';
  document.querySelector('#submit').disabled = true;

  // Stop form from submitting
  return false;
};
#submit:disabled {
  opacity: 0.5;
}
<h1>Tasks</h1>
<ul id="tasks">
</ul>
<form id="new-task">
  <input id="task" autocomplete="off" autofocus placeholder="New Task" type="text">
  <input id="submit" type="submit">
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...