简体   繁体   中英

Input box that converts text to buttons

I am trying to create a text input field that converts the input text to a "button" onblur. For example in the hotmail "new email page" when you enter email addresses it will make it into a little button-like object with a delete button when you enter a delimiter (semi-colon or comma). Anyone know how to do this?

I did a sort of workaround thing to what i want where i have a div with a border. In the div there is an input field with the borer invisible and a hidden button. I have a js function that takes the input value and makes the button visible with the value but this is not exactly what im looking for..

actually i just realised stackoverflow does this as well when im adding tags to the post

Here's a simple way to fake it (and it looks like this is similar to what SO does for tags):

  1. Create your text <input> , and make sure that its border and outline are both set to none.
  2. Create a container for your tags (or buttons, or whatever) and put it next to the <input> .
  3. Monitor the keydown event on the <input> ; when the user tries to enter a "break" character (such as a semi-colon or comma), create the button, add it to the container, empty the <input> 's value, and prevent default (so that the "break" character isn't inserted into the tag, or left in the <input> ).

That's the basic idea. Once you've done that, you can add event listeners/handlers to the buttons, or style them any which you'd like, etc.

Here's the simple example I cooked up :

var inp = document.getElementById('yourInput'),
    tags = document.getElementById('yourContainer'),
    breaks = {
        186: 1, // semi-colon
        188: 1 // comma
    };

function createTag(txt) {
    var elem = document.createElement('span');
    txt = document.createTextNode(txt);
    elem.appendChild(txt);
    elem.className = 'tag';
    tags.appendChild(elem);
}

function monitorText(e) {
    e = e || window.event;
    e = e.keyCode;
    if (breaks[e]) {
        e = inp.value;
        inp.value = '';
        createTag(e);
        return false;
    }
}

inp.focus();
inp.onkeydown = monitorText;

This is a multiple value field. Give a look at this one .

The feature is not so complex. It's an HTML list, and each value that you choose is converted into a LI node and appended to that list. The input field is inside the last LI, so its cursor can always be after the last choice. Besides, the input value is assigned to a hidden input, which can be used on the server-side as a comma-separated value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM