-1

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">

Chris Hemmens
  • 367
  • 2
  • 11

2 Answers2

0

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>
mfluehr
  • 2,832
  • 2
  • 23
  • 31
  • I can achieve the desired effect easier than that. I want to know if it's possible to style it in the desired way – Chris Hemmens May 31 '18 at 14:50
  • To make the clear button follow the text, you'll need JavaScript. – mfluehr May 31 '18 at 14:55
  • How do I go about doing this then? – Chris Hemmens May 31 '18 at 14:59
  • You'll need to dynamically calculate the width of the input's value. You can either do this based on the number of characters (easier but less accurate), or its actual value (harder but more accurate). See https://stackoverflow.com/questions/3392493/adjust-width-of-input-field-to-its-input for more info. – mfluehr May 31 '18 at 15:07
  • I've edited my response to use JavaScript, giving a result more like what you want. (I suggest adding a "JavaScript" tag to your question, if you're willing to use it.) – mfluehr May 31 '18 at 15:36
0

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>
Aniruddh Agarwal
  • 900
  • 1
  • 7
  • 22