How to "bypass" a word in the input whenever pressing the space key on the keyboard

Asked

Viewed 248 times

0

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

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

I don’t want anything self-completed, I just want that when the "space" is given the word is contorted. However, I have no idea how to do this.

  • There are already plugin for Jquery q do just that. I’ll see if I can find it and send it to you

  • An interesting plugin is the Tagit.

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>

I mean, you have a div class="tag-editor" that inside has an input. Each time space a span with the text that is written and another span inside the first with the symbol x 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>
<div class="tag-editor">
    <input type="text" tabindex="103" style="width: 536px;" />
</div>

  • Very good, only a "comments" tip in css should be used like this /* comentário */, why in some cases this causes problem in some browsers. + 1

  • @Guilhermenascimento haha, thank you. I know but I was distracted. I still haven’t gotten used to this snippet from the OS :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.