How to insert a TAG with a comma or semicolon

3

I found this project to insert TAGS into a form, but it just adds the TAG when enter key, and when that happens on my form it already sends! I would like to know what I should do in SCRIPT so that it adds the TAG every time I enter comma or semicolon ....

Example form:

SCRIPTCode:

<script>$(document).ready(function(){$('#addTagBtn').click(function(){$('#tagsoption:selected').each(function(){$(this).appendTo($('#selectedTags'));});});$('#removeTagBtn').click(function(){$('#selectedTagsoption:selected').each(function(el){$(this).appendTo($('#tags'));});});$('.tagRemove').click(function(event){event.preventDefault();$(this).parent().remove();});$('ul.tags').click(function(){$('#tags-field').focus();});$('#tags-field').keypress(function(event){if(event.which=='13'){if($(this).val()!=''){$('<liclass="addedTag">' + $(this).val() + '<span class="tagRemove" onclick="$(this).parent().remove();">x</span><input type="hidden" value="' + $(this).val() + '" name="tags[]"></li>').insertBefore('.tags .tagAdd');
                        $(this).val('');
                    }
                }
            });

  });

</script>
    
asked by anonymous 10.10.2016 / 02:02

2 answers

4

The line that detects enter is this:

if (event.which == '13') {

The code for enter is 13 , you can put other conditions:

if (event.which == 13 || event.which == 59 || event.which == 188  ) {

But it's important to note that this code looks at KeyCodes, not characters. This may have some variation depending on the keyboard map used.

Note also that I took the quotes, I do not understand the reason the original code does compare with strings.

To tell you the truth, for this you want, it would be better to look for a different script , or adapt this to rely on string and not the key pressed. For example, the numeric key enter no longer works on it.

Here's a test tool online:
link

Test with keys on the numeric keypad and the main keyboard to better understand the problem. Test also with ABNT2 and international keyboards, and you will notice that the code changes.

    
10.10.2016 / 02:18
2

It's in this stretch

$('#tags-field').keypress(function(event) {
    if (event.which == '13' || event.which == '191' || event.which == '188') {
        //...
    }
});

13 is the code for the enter key, change to 191 , which is the semicolon or 188 code that is the comma code.

As (well) noticed by Bacco, be careful because this validates the code of the key pressed and not the character itself, so it is subject to variations.

    
10.10.2016 / 02:19