clear input field data in jquery

Clear Input Field Data in jQuery

Input fields are commonly used in web development and sometimes it's necessary to clear the data inside them. In jQuery, this can be done easily with a few lines of code.

Method 1: Setting the Value to an Empty String

The first method to clear an input field in jQuery is by setting its value to an empty string. This can be done by selecting the input field and using the val() function to assign an empty string as the value.


$("input").val("");

This code selects all <input> tags on the page and sets their values to empty strings.

Method 2: Using the Reset Method

Another way to clear input fields is by using the reset() method. This method resets all form elements to their default values, including input fields.


$("form")[0].reset();

This code selects the first form on the page and resets all elements inside it to their default values.

Method 3: Removing the Value Attribute

The third method to clear input fields is by removing the value attribute from the input tag. This can be done using the removeAttr() function.


$("input").removeAttr("value");

This code selects all <input> tags on the page and removes their value attributes, which effectively clears the data inside them.

Choose the method that works best for you and implement it in your website or application to clear input fields with ease.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe