I want to add a clear button to a text field that floats after the text in the input. Is there an easy way to do this using a search type input field?
<input type="search">
I want to add a clear button to a text field that floats after the text in the input. Is there an easy way to do this using a search type input field?
<input type="search">
You can use JavaScript to copy the input's text into a hidden <span>
, and move the reset button according to the width of the <span>
. (This is inspired by https://stackoverflow.com/a/14855810/3469273.)
var search = document.getElementById("search"),
reset = document.getElementById("reset"),
measure = document.getElementById("measure");
search.addEventListener("input", onInput);
reset.addEventListener("click", onInput);
function onInput() {
measure.textContent = this.value;
reset.style.left = measure.offsetWidth + 'px';
console.log(measure.offsetWidth);
};
form {
position: relative;
margin: 1rem;
}
#search,
#measure {
padding: .5rem;
font-family: sans-serif;
font-size: 1rem;
white-space: pre; /* white-spaces will work effectively */
}
#search {
width: 100%;
}
#reset {
position: absolute;
left: 0;
top: 0;
height: 100%;
background: transparent;
border: none;
color: #999;
cursor: pointer;
}
#measure {
position: absolute;
left: -9999px;
top: -9999px;
}
<form>
<input id="search" type="search" />
<input id="reset" type="reset" value="X">
</form>
<span id="measure"></span>
I think you want a button to clear the content of the input Here's the code for the requirement:
<input id = "inputBox" class="inputBox" type="search">
<button class="clear-button" onclick="myfunction()">Clear</button>
<script>
function myfunction(){
document.getElementById("inputBox").value = ""
}
</script>