javascriptjqueryjquery-tags-input

Prepend text into each tag with specific ID


I have a tag system implemented into my website for three different categories. I set it up for a twitter account so I have "Keywords", "Mentions" and "Hashtags". What I need is that when a user inserts a tag in the text input for Mentions for it to prepend a "@" symbol before the text entered. The same goes for Hashtags except for the "#" symbol. I have put together a demo of what I have so far. Any help will be greatly appreciated.

JSFIDDLE

<div id="wrapper">
<table>
    <tr>
        <th></th>
        <td id="keyword-filter">
            <h5>Keywords</h5>
            <input type="text"  id="keywordInput">
            <br>
            Include:
            &nbsp;&nbsp;<input type="radio" name="keywordInclude" checked="true">Any
            &nbsp;&nbsp;<input type="radio" name="keywordInclude">All
            <b>Keywords</b>
        </td>

    </tr>

    <tr>
        <th></th>
        <td id="mention-filter">
            <h5>Mentions</h5>
            <input type="text"  id="mentionInput">
            <br>
            Include:
            &nbsp;&nbsp;<input type="radio" name="mentionInclude" checked="true">Any
            &nbsp;&nbsp;<input type="radio" name="mentionInclude">All
            <b>Mentions</b>             
        </td>

    </tr>

    <tr>
        <th></th>
        <td id="tag-filter">
            <h5>Hashtags</h5>
            <input type="text"  id="hashtagInput">  
            <br>
            Include:
            &nbsp;&nbsp;<input type="radio" name="tagsInclude" checked="true">Any
            &nbsp;&nbsp;<input type="radio" name="tagsInclude">All
            <b>Hashtags</b>
        </td>

    </tr>
</table>


Solution

  • According to the documentation and source code of the tagsInput plugin you can use the onAddTag callback to fire whenever a tag is added. You can grab the tag element which is just created in the DOM and prepend the text with a @. See the updated jsfiddle for a working example. You also need to check if the user didn't enter a @ already.

    $('#mentionInput').tagsInput({
        'defaultText':'add name',
        'onAddTag':function(tag) {
            var span = $('#mentionInput_tagsinput .tag span').last();
            if (span.text().substring(0, 1) != '@') {
                span.text('@' + span.text());
            }
        }
    });