There are plenty of solutions out there. Here is a google search with many examples:
javascript text input with clear button - Google Search[
^]
UPDATE
I decided to try this from the search above:
How to Put a Clear Button Inside an HTML Text Input Box?[
^]. It required a little tweak for working with razor pages, but worked fine.
Here is what I tried:
@model DataModel
@using (Html.BeginForm("Index", "Data", FormMethod.Get))
{
<fieldset class="text__host">
@Html.EditorFor(model => model.Name)
<button type="reset">×</button>
</fieldset>
}
CSS
.text__host {
position: relative;
width: 200px;
}
.text__host input {
width: 100%;
padding-right: 20px;
box-sizing: border-box;
}
.text__host input:placeholder-shown + button {
opacity: 0;
pointer-events: none;
}
.text__host button {
position: absolute;
border: 0;
display: block;
font-size: 12px;
top: 1px;
bottom: 1px;
right: 1px;
margin: auto;
background: #ddd;
padding: 0 10px;
outline: none;
cursor: pointer;
transition: .1s;
}
Here is how it behaves:
1. There is no "inset" button in the TextBox when there is no text.
2. Button is shown when there is text
3. Text is cleared when the button is pressed.
Best of all, no javascript was used!
UPDATE #2
I decided to have another look at this with a second input field and noticed that hte button cleared the whole form, not just the one text input.
So here is an updated solution for a per-input reset.
@model DataModel
@using (Html.BeginForm("Index", "Data", FormMethod.Get))
{
<fieldset class="text__host">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { placeholder = " " }})
<input type="button" class="button" onclick="resetInput('Name')" value="x">
</fieldset>
<fieldset class="text__host">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { placeholder = " " }})
<input type="button" class="button" onclick="resetInput('Title')" value="x">
</fieldset>
}
<script type="text/javascript">
function resetInput(id) {
document.getElementById(id).value="";
}
</script>
And the updated CSS:
.text__host input[type=text] {
width: 100%;
padding-right: 20px;
box-sizing: border-box;
}
.text__host input[type=text]:placeholder-shown + .button {
opacity: 0;
pointer-events: none;
}
.text__host .button {
position: absolute;
border: 0;
display: block;
font-size: 12px;
top: 1px;
bottom: 1px;
right: 1px;
margin: auto;
background: #ddd;
padding: 0 10px;
outline: none;
cursor: pointer;
transition: .1s;
}
Now, only the text field button clears it's own text field. Note how the text field
Id
is used.