jQuery Form How to - Clear nearby input text field when click an element








Question

We would like to know how to clear nearby input text field when click an element.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.6.2.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--  w  w  w.  jav a  2s  .  c  om-->
    $(document).ready(function () {
        $('.clearButton').click(function () {
           $(this).parent().find('input').val('');   
        }) 
    });
});
</script>
</head>
<body>
  <div>
    <input type="text" value="John Doe" /> <a href="#"
      class="clearButton">clear</a>
  </div>
  <div>
    <input type="text" value="Jane Doe" /> <a href="#"
      class="clearButton">clear</a>
  </div>
  <div>
    <input type="text" value="Joe Smith" /> <a href="#"
      class="clearButton">clear</a>
  </div>
</body>
</html>

The code above is rendered as follows: