Javascript очистка поля формы

События Формы

Рассмотрим основные события форм: отправка формы, очистка полей, фокус элемента формы, потеря фокуса, события для input, select, checkbox и многое другое.

Событие отправки формы

Слушать событие отправки формы можно при помощи submit .

 

Чтобы поймать событие отправки формы, используйте submit .

my_form.addEventListener("submit", () => < console.log("Событие отправки формы") >)

Очистка полей формы

Событие очистки полей формы.

my_form.addEventListener("reset", () => < console.log("Событие очистки полей формы") >)

Метод для очистки полей формы.

Невалидность полей формы

Событие invalid срабатывает при попытке отправить форму, когда одно или несколько полей формы неверно заполнены. Или не заполнены, когда поле имеет атрибут required .

my_form.addEventListener("invalid", (e) => < console.log("Значения формы не валидны"); >, true)

Как реализовать проверку правильности ввода данных, можете прочитать в статье про валидацию input.

События input, textarea

На input и textarea можно слушать следующие события:

  • input — событие ввода
  • change — событие изменения input (срабатывает после изменения поля и потери фокуса);
  • focus — выбор элемента, фокус;
  • blur — потеря фокуса;
  • select — выделение текста;
  • keyup — событие отпускание кнопки;
  • contextmenu — правый щелчок мыши.
const inputs = document.querySelectorAll(".form-events input"); inputs.forEach(el => < el.addEventListener("change", function () < // ваш код >) >);

Посмотреть когда срабатывают основные события форм, можете ниже.

События select

Для элемента select можем отслеживать следующие события:

  • change — выбор элемента из списка (option);
  • focus — фокус на select;
  • blur — потеря фокуса select.
 
my_select.addEventListener("change", () => console.log("Выбран пункт из списка select"));

В примере ниже посмотрите, когда какие события срабатывают для элемента формы select .

Если вам интересно как стилизуется select, вот ссылка на статью.

События checkbox / radio

Для checkbox / radio можно использовать следующие события:

checkb.addEventListener("change", () => console.log(checkb.value)); radio.addEventListener("click", () => console.log(radio.value));

Здесь вам пригодятся знания, как проверить состояние чекбокса.

События range

Для input type range используют следующие события:

  • change — происходит в момент отпускания кнопки;
  • input — происходит в режиме реального времени.
range.addEventListener("change", () => console.log(range.value));

Источник

Javascript очистка поля формы

Last updated: Jan 12, 2023
Reading time · 3 min

banner

# Table of Contents

# Clear an Input field after Submit

To clear an input field after submitting:

  1. Add a click event listener to a button.
  2. When the button is clicked, set the input field’s value to an empty string.
  3. Setting the field’s value to an empty string resets the input.

Here is the HTML for this example.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> input type="text" id="first_name" name="first_name" /> button id="btn" type="submit">Submitbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick(event) // 👇️ if you are submitting a form (prevents page reload) event.preventDefault(); const firstNameInput = document.getElementById('first_name'); // Send value to server console.log(firstNameInput.value); // 👇️ clear input field firstNameInput.value = ''; >);

We added a click event listener to the button.

Every time the button is clicked, the handleClick function is invoked, where we set the value of the input to an empty string.

# Clear multiple input fields after submit

To clear the values for multiple inputs after submitting:

  1. Use the querySelectorAll() method to select the collection.
  2. Use the forEach() method to iterate over the results.
  3. Set the value of each input field to an empty string to reset it.
Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> input type="text" id="first_name" name="first_name" /> input type="text" id="last_name" name="last_name" /> button id="btn" type="submit">Submitbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick(event) // 👇️ if you are submitting a form event.preventDefault(); const inputs = document.querySelectorAll('#first_name, #last_name'); inputs.forEach(input => input.value = ''; >); >);

We used the document.querySelectorAll method to select a NodeList containing the elements with IDs set to first_name and last_name .

The method takes a string that contains one or more valid CSS selectors.

The function we passed to the NodeList.forEach method gets invoked with each input in the NodeList .

In the function, we set the value of each input to an empty string.

# Clear all form fields after submitting

To clear all form fields after submitting:

  1. Add a submit event listener on the form element.
  2. When the form is submitted, call the reset() method on the form.
  3. The reset method restores the values of the input fields to their default state.

Here is the HTML for this example:

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> form action="" id="my_form"> input type="text" id="first_name" name="first_name" /> input type="text" id="last_name" name="last_name" /> button id="btn" type="submit">Submitbutton> form> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const form = document.getElementById('my_form'); form.addEventListener('submit', function handleSubmit(event) event.preventDefault(); // 👇️ Send data to the server here // 👇️ Reset the form here form.reset(); >);

We added a submit event listener to the form element.

The event fires when a form is submitted.

We used the event.preventDefault() method to prevent the page from reloading.

The reset() method restores a form’s elements to their default values.

If you need to show/hide a form on button click, check out the following article.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

JavaScript Clear Input

JavaScript Clear Input

  1. Use the onfocus Attribute to Vanish Input Field in JavaScript
  2. Use Conditional Statement to Clear Form Input Value in JavaScript
  3. Use the reset() Method to Erase Form Input Fields in JavaScript

In JavaScript, we usually consider a specific property to deal with the input value. The value property along with the getElementById() method grabs an input field’s detail.

Later, we can perform some conditions based on the entry. Again, we can also depend on some HTML attributes to connect the input elements and JavaScript functions.

Here, we will present some examples that can be implemented in multiple ways.

Use the onfocus Attribute to Vanish Input Field in JavaScript

We will initially declare an input field with a defined value for this example. Also, the input element will jump to perform the function clearF(this) as soon the cursor will point or focus in the input box.

If the function’s condition is served, it will remove the value, and thus the input gets cleared.

 html> head>  meta charset="utf-8">  meta name="viewport" content="width=device-width">  title>testtitle>  head> body> input type="text" value= "abc@gmail.com" onfocus="clearF(this)"> script>  function clearF(target)   if (target.value == 'abc@gmail.com')   target.value = "";  >  >  script>  body>  html> 

Its content vanishes as the cursor is placed and clicked on the input field. The this refers to its value for the specific element.

Use Conditional Statement to Clear Form Input Value in JavaScript

According to a form submission, it is necessary to have a corresponding button element to store data. We will take a form element, and the button associated with it will carry an onclick attribute to fire a function.

The function will check if the input field is empty or not. If it finds any content, it will simply reinitialize it empty.

 html> head>  meta charset="utf-8">  meta name="viewport" content="width=device-width">  title>testtitle>  head> body>  form> input type="text" id="name">  input type="button" value="clear" onclick="clearF()">  form> script>  function clearF()   var grab = document.getElementById("name");  if (grab.value !="")   grab.value = "";  >  >  script>  body>  html> 

Here, we have an instance of the grab form that will take the id . When the button is clicked, the function will check if the input is empty, and it will perform just as the conditional statement describes.

Use the reset() Method to Erase Form Input Fields in JavaScript

We will also examine a form to clear its input by the reset() method. All it will need is to create an instance of the form, and on the button click, it will reset the whole form vanishing the inserted contents.

 html> head>  meta charset="utf-8">  meta name="viewport" content="width=device-width">  title>testtitle>  head> body>  form id="Form">  Name: input type="text">br>br>  input type="button" onclick="myFunction()" value="Reset form">  form>  script> function myFunction()   document.getElementById("Form").reset(); >  script>  body>  html> 

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

Related Article — JavaScript Input

Источник

как очистить input js

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

Например, мы хотим очистить поле ввода для поиска музыки. Тогда наш код будет выглядеть так:

 type="text" id="searchInput" placeholder="Введите название песни или исполнителя" />  onclick="clearSearch()">Очистить function clearSearch()  document.getElementById('searchInput').value = ''; >  

При нажатии на кнопку «Очистить» значение поля ввода будет заменено на пустую строку, тем самым произойдет очистка.

Источник

Clearing the input field value in JavaScript

In this tutorial, we are going to learn about how to clear the input field value in form using the JavaScript.

We mostly clear the form input field values after submitting a form or clearing the cluttered form.

Clearing the input field value with button

Consider we have a following input field value with a button element.

input type="text" placeholder="Name" id="name"/> button id="btn">Clear input fieldbutton>

To clear the above input field by clicking a Clear input field button, first we need to access these elements inside the JavaScript by using document.getElementId() method.

const inputField = document.getElementById("name"); const btn = document.getElementById("btn");

Now, we need to attach a click event to the button element and set a inputField.value property to an empty string » » .so that when a user clicks on the button , input field value is cleared.

btn.addEventListener('click',()=> // clearing the input field inputField.value = " "; >)

Источник

Читайте также:  Знакомство с GET-запросами
Оцените статью