开发者

Clear search box on the click of a little "x" inside of it

I'm working on a search form for a t开发者_如何学Goumblr theme. I'm wondering if there's any simple JavaScript, CSS, or jQuery solution that when a little tiny "x" image inside the textbox is clicked, it clears the form? An example of this is on apple.com. Here's the search code I'm working with:

<form id="search" action="/search">
    <p>
        <input type="text" name="q"  placeholder="Search&hellip;" />
    </p>
</form>


It is not INSIDE actually...

Try this:

<span class="search"><img src=lookup><input type=text ><span>x</span></span>

with the style:

span.search 
  {
    display:inline-block;
    border:1px solid black;
    border-radius:0.5em; 
    -webkit-border-radius: 0.5em;    
  }
span.search > input 
  {
    background: none;
    border: none;
  }


To expand on kingjv's solution, this is a simple plugin:
http://jsfiddle.net/PvFSF/

(function ($, undefined) {  
    $.fn.clearable = function () {  
        var $this = this;  
        $this.wrap('<div class="clear-holder" />');  
        var helper = $('<span class="clear-helper">x</span>');  
        $this.parent().append(helper);  
        helper.click(function(){  
            $this.val("");  
        });  
    };  
})(jQuery);

$("#myInput").clearable();


It's only a css trick. If you see apple.com, what they're doing is to put the delete image after the text, but it seems to be inside. Here you have the code to accomplish this effect:

<style>
  #searchContainer{
    border-width: 1px;
    border-style: solid;
    display: inline;
  }
  #q{
     border: none;
  }
</style>
<script>
  $(document).ready(function(){
     $("#clear").click(function(){
        $("#q").val(""); //Clear the text input
     });
  });
</script>
<form id="search" action="/search">
    <p>         
        <div id="searchContainer">
          <input type="text" name="q" id="q" />
          <span id="clear">x</span> <!-- You can use an image here instead -->
        </div>
    </p>
</form>

It's tested & running :)
Hope this helps. Cheers


If you look at the source of Apple's site you'll see their search textbox is really a div, a textbox, then another div. It's these outer divs that hold the things like the x to clear it out.


You can do something like this:

http://jsfiddle.net/nByBB/

probably want to make it a bit nicer of course but it illustrates the idea.


using css give your input field right padding of, let's say 20px. Then make an image of (X) [and let's say your image has width of 20px and is called clear.png], include <img class="clearingImage" src="/imagepath/clear.png" style="position:relative;left:-20px;" /> right after your tag and then in your javascript block you say

$('img.clearingImage').click(function () {
   $(this).prev().val('');
});

keeping in mind that the image is positioned on the same line right after the input tag

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜