Ways to show a div element within an input field?

I want to incorporate tags similar to stackoverflow on my website. Users will be able to create tags for filtering results, searching, showcasing expertise, and more.

I have managed to create tags, but I am struggling to display them inside an input box like stackoverflow. The issue lies with the margin between tags. Every time a tag is created, it appears aligned but without any space or margin. Currently, all tags are displayed inline without any separation.

The jQuery code I have experimented with is:

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

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

I also tried displaying the tags within an 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');
}

Unfortunately, this approach did not yield the desired result.

Jsfiddle

Answer №1

Simply put: It's not possible to fake it, but you can create the illusion that you are achieving it.

For a more detailed explanation, check out this 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(); });
});

Answer №2

It is not possible to insert a div within an input tag. When attempting to add a tag within an input tag on stackoverflow, right clicking on the input tag and selecting Inspect Element will reveal that they use a span tag instead, placed outside the input tag itself.

<div>
   <span >  //used for the tags
  <input />
</div>

Answer №3

$(function(){
 var oldVal;         
 $("#inputtext").change(function(e){    
       oldVal= $(this).val();    
 });   

 $("#inputtext").keypress(function(e){        
    var valueofinput= $(this).val().replace(oldVal,'');
     if(e.which==13)
    {
        $('.tag').append("<span>"+valueofinput+"</span>&nbsp;");         
        $('.tag').show();
    }        
 });    
});

css

.tag
{
 height:auto;
 width:auto;
 background:white;
 color:white;
 text-align:center;
 display:none;
 position:absolute;
 padding:5px;    
 margin:1em;
}

.tag > span
{
  background:green;
}

http://jsfiddle.net/Hb8yj/14/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a loading spinner dialog using Jquerymobile until the page finishes loading

I am facing an issue with my app where I need to show a Loading dialog while sending data from the first page to the server. The goal is to display the Loading dialog until the send operation (posting to server) is complete and then proceed to page two. I ...

Enhancing fancybox with dynamic scrollbars as the window size changes

I'm currently working on a popup form that I'm displaying with Fancybox 2 by using the code below: $(link).fancybox({ type: 'iFrame', autoSize: false, autoScale: false, width: '1280px', height: '1024p ...

After reaching the conclusion, the code restarts

Any ideas on how to reset this code every 10-20 seconds? I'm struggling to find a solution! I'm new to coding, so any assistance would be greatly appreciated. Here's the code: var items = document.getElementsByClassName('btn-primary n ...

Eliminate the custom button feature from the Datatable

https://i.sstatic.net/7ndvv.png Is there a way to hide the Copy, CSV, Excel, PDF, and Print buttons located in the top right corner of the datatable? These seem to be default features of datatables, but I have been unable to find any information on how to ...

Personalizing the structure of a joomla template

Having some trouble customizing my Helix Framework template. I'm trying to adjust the width of the page to be 1140 px. When I make changes in the framework menu, it only adjusts the text field width and not the graphics. How can I achieve the layout s ...

Adjust the size of the div menu according to the window's dimensions

Is there a way to make a menu that will resize both the width and height of the window? I've managed to resize the width using %, but for some reason, the height isn't cooperating. I've experimented with max-width/height settings and tried ...

Update the second dropdown list based on the selection made in the first dropdown list in Vue.js

My goal is to dynamically change the options in the second select list based on the value selected in the first one. I initially achieved this by creating two separate Vue instances for each select, but I wanted a more streamlined approach for a cleaner ap ...

Attempting to replace onbeforeunload during initial stage of form wizard

I am working on a form wizard that consists of 5 steps. My main concern is preventing users from accidentally losing their form data when navigating between steps 2-4. I have implemented a flag for the submit function, but now I need to add one for the f ...

`Videos on youtube with elements overlapping each other`

Having an issue with YouTube videos where other elements (LayerSlider) are overlapping on top of them. You can see the problem by clicking on this link () and trying to make the video fullscreen. I found a similar issue mentioned in the following link: Y ...

What's the best way to maintain the return type of a function as Promise<MyObject[]> when using forEach method?

I am currently working with a function called search, which at the moment is set up to return a type of Promise<MyObject[]>: export function search(args: SearchInput) { return SomeInterface.performSearch(args) .then(xmlRequest =&g ...

Retrieving a variable value set within a jQuery function from within an Angular 2 component

In the current project, I am facing a situation where I need to work around and initialize jQuery datetimepicker inside an Angular 2 application (with plans to refactor it later). However, when I assign a datetime value to a variable, I encounter a proble ...

Maintain the flow of a floated or absolutely positioned element using CSS

Is there a way in CSS to ensure that floated or absolutely positioned elements remain within the flow? I find it frustrating that CSS lacks something like flow:on and flow:off to control this. The main issue I am facing is with having a div element of var ...

Incorporate pictures from the popup onto the main page

I have developed a basic PHP image editor script where users can select images from galleries and merge them together. However, I am facing an issue: The galleries open in a popup while the editor area is on the parent page. I am looking for a JavaScript ...

Ways to position Drop-down menu flush against the left edge of the webpage?

I am facing a challenge in customizing my CSS3 Mega drop-down menu. I want the mega menu to start from the left side of the main page, beginning from the home button area and extending all the way to the end. Currently, it is appearing where the parent men ...

Adding a box shadow around the entire div in Internet Explorer 11 with CSS

I am having difficulty applying box-shadow to create a shadow around the entire perimeter of a div. While it works in FireFox, it does not work in IE 11. So far, I have attempted solutions from this StackOverflow thread. For reference, here is a JSFiddle ...

Steps for Integrating a Web Service Reference in NodeJS

Can a Web reference be added to a NodeJS project similar to how it's done in .NET framework Web API Projects? Essentially, the NodeJS API project will serve as a middleware between the Front End and an XML Web service. The XML Web service is a secure ...

Modifying css background in real-time based on the current weather conditions

Is there a way to dynamically change the background image in CSS based on the weather condition? I'm utilizing the wunderground API to retrieve the weather data, which is stored in the weather variable. I am struggling with how to update the backgrou ...

Angular's onreadystatechange event is triggered when the state

Hey there, I'm new to Angular and had a question. Is it possible to use the $http service in Angular to trigger a function whenever there is any change in the ready state/status, not just for success or failure? If so, what would be the equivalent ang ...

Using jQuery and C# (.Net 8) to send an array of form files from Ajax to Controller

Currently, I am working on a .Net 8 API project and facing an issue with passing multiple files along with other form elements to the controller using ajax. While I have been successful in passing a single file, I am unable to pass an array of files as ex ...

Using v-bind to dynamically set styles in Vue.js

While utilizing v-bind:style to apply dynamic values, I encountered an issue where v-bind:style did not seem to work. However, in the console, I verified that v-bind:style was receiving the correct value (:style='{ color : red (or any other value) }&a ...