2

I want Clear button like this in front of every textbox to clear its text. You can see this type of clear buttons in Internet Explorer. But that's IE's default functionality.

I can only use CSS, HTML and JAVASCRIPT.. unfortunately I can't use Jquery. So is there any method to do this?

Thanks

enter image description here

Faizan
  • 1,102
  • 2
  • 12
  • 23

2 Answers2

0

Demo

javascript

document.getElementById('inputClear').onclick = function () {
    document.getElementById('inputText').value = "";
};

html

<span class="deleteicon">
    <input id="inputText" value="input here" type="text" />
    <span id="inputClear"></span>
</span>

css

span.deleteicon {
    position: relative;
}
span.deleteicon span {
    position: absolute;
    display: block;
    top: 4px;
    right: 4px;
    width: 16px;
    height: 16px;
    background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
    cursor: pointer;
}
span.deleteicon input {
    padding-right: 20px;
}
4dgaurav
  • 10,721
  • 4
  • 27
  • 55
0

JavaScript

window.onload = function(){
  var span = document.getElementsByClassName('clear'), i;
  for(i = 0; i < span.length; i++){
    (function(i){
      span[i].onclick = function(){
        span[i].parentNode.getElementsByTagName('INPUT')[0].value = ''; 
      };
    })(i);
  }
};

HTML

<form>
  <div class="wrapper">
    <input type="text" name="firstname" value="" class="textbox" />
    <span class="clear">x</span>
  </div>
  <div class="wrapper"> 
    <input type="text" name="lastname" value="" class="textbox" />
    <span class="clear">x</span>
  </div>
</form> 

CSS

.clear{
  position:absolute;
  top:2px;
  right:5px;
  cursor:pointer;
}

.textbox {
   width:100%;
}    

.wrapper {
  width:200px;     
  position:relative;
}  

Working jsBin


A sidenote to the other answers: Assuming that there's only one element and using getElementById('clear') isn't a good idea.

hex494D49
  • 8,125
  • 3
  • 34
  • 44