Modelesq
Modelesq

Reputation: 5402

Click on a div, add it to the search query input

I'm basically trying to allow the user to click on a 'recent search tag' and add it to the search input in full. What I mean by 'in full' is the tags' styling along with text.

For example:

When clicking on a recent search tag, add it to search.

I know there's a jquery plugin for this. But I really wanted to know if there was a simple approach in getting this done.

I have a jsfiddle. Right now when I click on the recent search tag, it takes the text of each div and one at a time.

$('.tag').click(function(e){
     var tag = $(this).children().html();
     $('input').val(tag);
     e.preventDefault();
});

Any help is greatly appreciated. Thanks!

Upvotes: 0

Views: 150

Answers (2)

MikeM
MikeM

Reputation: 27415

you can get the styled tags to show "in" the input box by placing them under the input (w/transparent bg) (similar to what Google does with their autocomplete functionality)

Setup some markup around the input (input wrapper and a container for the tags):

<div class="input-group">
    <div class="tag tag-input"></div>
    <input name="q" id="search" class="input-text" multiple="multiple" placeholder="Search..." autocomplete="on" value="" />
</div>

Position the tag-input to be inline with the text, set the input to a wider word-spacing so the tags are spaced equally. Set the tag-input z-index lower than the input's. It'll also adjust the input width as the user types a long query.

jsfiddle (fullscreen)

This uses the oninput event (ala $input.bind('input'...) which works in modern browers (see On input change event? for more info on that)

Upvotes: 1

user1726343
user1726343

Reputation:

$('.tag').click(function(e){
    var tag = $(this).children().html();
    $('input').val(function(i,v){return v+" "+tag});
    e.preventDefault();
});

will add tags instead of replacing them.

Upvotes: 0

Related Questions