- как очистить input js
- Using JavaScript to reset or clear a form
- Simple example for clearing all form elements using JavaScript
- Illustrating the difference between resetting and clearing a form
- See Also
- How to reset or clear a form using JavaScript?
- Syntax
- Algorithm
- Creating a user form
- Defining script or function to remove
- Example
- Conclusion
- Очистить форму кнопкой javascript
как очистить input js
Как видно из кода, принцип довольно прост и заключается в присвоении пустой строки свойству value этого элемента.
Например, мы хотим очистить поле ввода для поиска музыки. Тогда наш код будет выглядеть так:
type="text" id="searchInput" placeholder="Введите название песни или исполнителя" /> onclick="clearSearch()">Очистить function clearSearch() document.getElementById('searchInput').value = ''; >
При нажатии на кнопку «Очистить» значение поля ввода будет заменено на пустую строку, тем самым произойдет очистка.
Using JavaScript to reset or clear a form
Using an HTML ‘Reset’ button is an easy way to reset all form fields to their default values. For instance, the code snippet below shows an field of type “reset”, which on being clicked resets all the form fields:
input type="reset" value="Reset Form">
In fact, we could also use the form’s reset() method to achieve the same effect, using a simple button element:
input type="button" value="Reset Form" onClick="this.form.reset()" />
These methods are very convenient to use, but they do not provide the functionality of clearing all the fields, including their default values. In order to achieve this, we would need to write a JavaScript function that would clear each individual field’s value.
Simple example for clearing all form elements using JavaScript
Let us look at an example of a simple form
form name="data_entry" action="#"> Company Name: input type="text" size="35" name="company_name"> Select Business Type: input type="radio" name="business_category" value="1"> Manufacturer input type="radio" name="business_category" value="2"> Whole Sale Supplier input type="radio" name="business_category" value="3"> Retailer input type="radio" name="business_category" value="4"> Service Provider Email Address: input type="text" size="30" name="email"> Keep Information Private: input type="checkbox" name="privacy"> input type="button" name="reset_form" value="Reset Form" onclick="this.form.reset();"> input type="button" name="clear" value="Clear Form" onclick="clearForm(this.form);"> form>
As you can see, the first button simply resets all the fields using this.form.reset() as described earlier. Let us now write the JavaScript function that behaves as the onClick handler for the second button in the above form.
- In this function, we would first need to acquire a reference to all the elements in the form object:
var frm_elements = oForm.elements;
where, oForm is a reference to the form object passed to the function using this.form as shown in the form above. oForm.elements is now a Javascript array that holds a reference to each of the form elements.
- We would then have to iterate over the individual form element objects of the frm_elements array (Step 1), using a for-loop construct:
for(i=0; ifrm_elements.length; i++) // code for accessing each element goes here >
- We can find out the type of each form element in the frm_elements array by retrieving it’s type property:
field_type = frm_elements[i].type.toLowerCase();
- If frm_elements[i] holds a reference to any of the , , and elements, it’s value can be cleared by simply setting it to an empty string:
In case of radio and checkbox elements, we would use a different approach:
if (frm_elements[i].checked) frm_elements[i].checked = false; >
If frm_elements[i] is an object of the type select (either select-one or select-multi), we can set the selectedIndex property to -1:
frm_elements[i].selectedIndex = -1;
for (i = 0; i frm_elements.length; i++) field_type = frm_elements[i].type.toLowerCase(); switch (field_type) case "text": case "password": case "textarea": case "hidden": frm_elements[i].value = ""; break; case "radio": case "checkbox": if (frm_elements[i].checked) frm_elements[i].checked = false; > break; case "select-one": case "select-multi": frm_elements[i].selectedIndex = -1; break; default: break; > >
Have a look at the demo to see how it works, and compare the result of clicking the reset button and the button with the custom onClick handler that we have just coded. You can also download the code from here.
Illustrating the difference between resetting and clearing a form
As the above demo illustrates, the two buttons function similarly, for this particular form, because none of the values of the elements in this form are set on page load. So the difference between the functioning of the two buttons is not visible. Let us set default values for some of the form elements. For instance, the following snippet of code sets the default for the radio element named “business_category” to the value 3.
input type="radio" name="business_category" value="1">Manufacturer input type="radio" name="business_category" value="2">Whole Sale Supplier input type="radio" name="business_category" value="3" checked>Retailer input type="radio" name="business_category" value="4">Service Provider
Likewise, we can also set defaults for a few other form elements. See this demo, for an example and compare it with the previous one. As you must have noticed, the difference is now obvious, as the Reset button does not clear the default values, unlike the other button, which does.
See Also
How to reset or clear a form using JavaScript?
This tutorial teaches us how to reset or clear a form using JavaScript. This option is very helpful for users in the situation where they have filled the wrong form and before submitting they get to know about it and now they want to delete all the data. If the form is too large then manually deleting everything may be hard so it’s better to use the reset() method of JavaScript.
The reset() method is defined in JavaScript and by just clicking on it the form which will be linked to its onclick() method will reset every input section of the provided form.
Syntax
We have seen the basics of the reset() function, now let’s move to its syntax −
var element = document.getElementById( Id_of_required_form ). element.reset()
In the above syntax, “Id_of_required_form” is the id of the form which we want to reset or clear. We have used the ‘getElementById’ method of the DOM to get the form and stored that in a variable name ‘element’.
After that, by using the method reset() we reset or clear the form with the id ‘Id_of_required_form’ element by calling it.
Algorithm
We have seen the syntax to reset or clear a form by getting its id and reset() method, let’s see the complete algorithm step by step to understand it in a better way −
Creating a user form
In these steps, we will create the form in which we will define or create many input boxes for user input to fill the form and a button which will call the function to delete the object from the dropdown list.
- Initially, we have to create a form using the tag which we want to reset or clear using the reset() method of JavaScript.
- In the form, we have created some input boxes by using the tag where the user can write the data.
- These input spaces will be of type text and number to get the user input in the required type.
- In the form after defining ‘inputs’ to take user input, we will define an input field using the tag and will make it of type button and we will define the ‘onclick’ event which will call the function which we will define later in the script.
Defining script or function to remove
In these steps, we will define the function which will be called in the ‘onclick’ event of the above-defined button.
- Initially, we will create a function using the ‘function’ keyword and will give it a name that will be called in the ‘onclick’ event.
- In the defined function we will create a variable to store the return value from the call to the ‘document.getElementById()’ method.
- We will pass the ‘id’ of the above-defined form as the parameter to the call to the ‘document.getElementById()’ method.
- By using the reset method with the variable (which contains the return value of the call to the method) we can reset every input field to empty.
These are the basic steps to reset or clear a form using JavaScript, now let’s see some examples to get a better understanding of the above-defined steps.
Example
In this example, we are going to implement the above-defined algorithm step by step, let’s implement the code −
!DOCTYPE html> html> body> h3>Fill out the below-given form and click the reset button to see the working of the reset() function in JavaScript./h3> form id=" form_id "> Student Name br> input type="text" name="sname"> br> Student Subject br> input type = "password" name = "ssubject" > br> Student Roll Number br> input type = "roll_no" name = "roll_number" > br> input type = "button" onclick = "newFunction()" value = "Reset" > /form> script> function newFunction() var element = document.getElementById(" form_id "); element.reset() > /script> /body> /html>
In the above output, we got one form in which there are some input spaces, where the user can provide some input and at last, there is a reset button which will reset the form to the original or initial form.
Conclusion
In this tutorial, we have learned the method to reset or clear the HTML form using JavaScript. This is only possible if while defining the HTML form programmer defines or creates a button for the user to reset the form otherwise the user has to reset it manually.
The reset() function is defined in JavaScript and by just clicking on it the form which will be linked to its onclick() method will reset every input section of the provided form. Also, if there is any pre-defined value is there present for any input it will get that value.
Очистить форму кнопкой javascript
Для отправки введенных данных на форме используются кнопки. Для создания кнопки используется либо элемент button :
С точки зрения функциональности в html эти элементы не совсем равноценны, но в данном случае они нас интересуют с точки зрения взаимодействия с кодом javascript.
При нажатии на любой из этих двух вариантов кнопки происходит отправка формы по адресу, который указан у формы в атрибуте action , либо по адресу веб-страницы, если атрибут action не указан. Однако в коде javascript мы можем перехватить отправку, обрабатывая событие click
При нажатии на кнопку происходит событие click , и для его обработки к кнопке прикрепляем обработчик sendForm . В этом обработчике проверяем введенный в текстовое поле текст. Если его длина больше 5 символов, то выводим сообщение о недостимой длине и прерываем обычный ход события с помощью вызова e.preventDefault() . В итоге форма не отправляется.
Если же длина текста меньше шести символов, то также выводится сообщение, и затем форма отправляется.
Также мы можем при необходимости при отправке изменить адрес, на который отправляются данные:
function sendForm(e)< // получаем значение поля key var keyBox = document.search.key; var val = keyBox.value; if(val.length>5) < alert("Недопустимая длина строки"); document.search.action="PostForm"; >else alert("Отправка разрешена"); >
В данном случае, если длина текста больше пяти символов, то текст отправляется, только теперь он отправляется по адресу PostForm , поскольку задано свойство action:
document.search.action="PostForm";
Для очистки формы предназначены следующие равноценные по функциональности кнопки:
При нажатию на кнопки произойдет очистка форм. Но также функциональность по очистке полей формы можно реализовать с помощью метода reset() :
function sendForm(e)< // получаем значение поля key var keyBox = document.search.key; var val = keyBox.value; if(val.length>5) < alert("Недопустимая длина строки"); document.search.reset(); e.preventDefault(); >else alert("Отправка разрешена"); >
Кроме специальных кнопок отправки и очистки на форме также может использоваться обычная кнопка:
При нажатии на подобную кнопку отправки данных не происходит, хотя также генерируется событие click:
При нажатии на кнопку получаем введенный в текстовое поле текст, создаем новый элемент параграфа для этого текста и добавляем параграф в элемент printBlock.