How to "bypass" a word in the input every time you press the space key on the keyboard

0

As the question already says, I want to "bypass" a word whenever it gives a space, as in the examples below:

I do not want anything to self-complete, I just want it when you give the "space" the word goes around. But I have no idea how to do it.

    
asked by anonymous 28.12.2014 / 02:22

1 answer

3

If you see the HTML generated by this input you can see this:

<div class="tag-editor" style="width: 666px; height: 26px; opacity: 1; z-index: 1; position: relative;">
    <span>
        <span class="post-tag">tag_a
            <span class="delete-tag" title="remover esta tag"></span>
        </span>
        <span class="post-tag">tag_b
            <span class="delete-tag" title="remover esta tag"></span>
        </span>
    </span>
    <input type="text" tabindex="103" style="width: 536px;" /><span></span>
</div>

That is, you have a div class="tag-editor" that inside has an input. Each time you press space , a span is generated with the text that is written and another span inside the first with the x symbol to allow removal.

The code to do what you ask is, using the HTML above:

$(".tag-editor input").on('keydown', function (e) {
    if (e.keyCode == 32) {
        e.preventDefault(); // para prevenir criar um espaço
        var tag = this.value;
        if (!tag) return;   // no caso de não haver nada escrito ainda
        $(this).before('<span>' + tag + '<span class="remover">x</span></span>');
        this.value = '';    // limpar o input para nova tag
    }
});

$(".tag-editor").on('click', '.remover', function (e) {
    $(this).parent().remove(); // remover a tag clicada
});
.tag-editor {
    border: 1px solid black;
}

.tag-editor > span {
    background-color: #ccf;
    padding: 0 2px;
    margin: 0 2px;
    border-radius: 5px;
}

.tag-editor span span { /* para o "x" que remove a tag */
    margin-left: 2px;
    color: #88b;
    cursor: pointer;
    margin-left: 3px;
}

.tag-editor input { /* para remover aspeto tipico de input */
    border: none !important;
}

.tag-editor input:focus { /* para remover aspeto tipico de input */
    outline: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><divclass="tag-editor">
    <input type="text" tabindex="103" style="width: 536px;" />
</div>
    
28.12.2014 / 09:49