What is the best method to clear text in a text field, when the user clicks on it?
I.e., if the text search field says "search" and when they click it, it clears the value.
The <input> tag, helps you to take user input using the type attribute. To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.
To clear an input field with React, we can set the value of the value attribute to an empty string. We create the val state with the useState hook. Then we set the value prop of the input to the val state. Next we set the onClick prop of the button to a function that calls setVal to an empty string.
To clear an input field after submitting: Add a click event listener to a button. When the button is clicked, set the input field's value to an empty string. Setting the field's value to an empty string resets the input.
You could do like:
<input type="text" onfocus="if(this.value == 'search') {this.value=''}" onblur="if(this.value == ''){this.value ='search'}">
<input name="foo" placeholder="Search" />
The placeholder tag is a new HTML5 tag that does exactly what you want to do here.
Normal HTML:
<script type="text/javascript">
function clearThis(target){
target.value= "";
}
</script>
<input type="text" value="Search" onfocus="clearThis(this)" />
jQuery:
<script type="text/javascript">
function clearThis(target){
$(target).val = "";
}
</script>
<input type="text" value="Search" onfocus="clearThis(this)" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With