Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display div inside input tag?

I am trying to create tags like stackoverflow for my website, a user on my website will be creating tags for filtering results or many other operations like search, expertise etc.

I am able to create tag but not able to show it inside input box as we do in stackoverflow, there is problem with margin between tags. Every time when i create tag it is aligned but has no space or margin. Currently it is showing all tags inline without any space.

jQuery i tried-

$(function () {        
    $("#inputtext").keypress(function (e) {
        var valueofinput = $(this).val();
        if (e.which == 13) {
            $('.tag').html(valueofinput);
            $('.tag').show();
        }
    });

    $('.tag').click(function () {
        $(this).hide();
    });        
});    

However i tried showing it in input tag like this-

if(e.which==13)
{
$("#inputtext").val().addClass('tag').css('display','inline-block');
}
if(e.which==32)     //for space
{
$('.tag').css('margin-left','5px');
}

But this doesn't work.

Jsfiddle

like image 647
Manoz Avatar asked Jul 30 '13 04:07

Manoz


2 Answers

Short answer: You can't/don't. But you can give the appearance that you are.

Longer answer: Example

$(function(){    
    $("#inputtext").keypress(function(e){
        var valueofinput= $(this).val();
        if(e.which==13)
        {
            $('#inputtext').before('<span class="tag">' + valueofinput + '</span>');
            $('input').val('');
        }
    });
    $(document).on('click', '.tag', function(){
        $(this).remove();
    });
    $('.inputholder').click(function() { $('#inputtext').focus(); });
});
like image 162
musicnothing Avatar answered Nov 01 '22 10:11

musicnothing


You can't insert a div in an input tag. Here in stackoverflow, if you try adding a tag in the input tag, then right click on the input tag then click on Inspect Element, you will see that they are adding span tag, but not inside the input tag itself.

<div>
   <span >  //for the tags
  <input />
</div>
like image 44
meborda Avatar answered Nov 01 '22 09:11

meborda