1

I have a text input that gets updated every time a user selects a new tag (a new creates a new list element) and these list elements are mapped into a comma separated list that is then added to the value a text input.

The value of the text input may look like this,

PHP, C#, C, C++

A user can click on a tag to remove it from text input, however I cannot see to remove it from the comma seperated list in the input field.

My code looks like this for the tag deletion method.

var array = $("#job_tags_input").val().split(",");

I though this would give an array of the values in my input but all I get in my console hwen I do my console.log(array) is,

["C", " PHP", " Perl", " C#", " "]

If the tag for "C" was deleted how would I remove that from my input field?

MY JS

if($("#job_tags").get(0)) {
    $("#job_tags").tagHandler({
        assignedTags: [ 'C', 'Perl', 'PHP' ],
        availableTags: [ 'C', 'C++', 'C#', 'Java', 'Perl', 'PHP', 'Python' ],
        autocomplete: true,
        onAdd: function(tag) { 
            var s = $("#job_tags li").map(function(){
                return $(this).text();
            }).get().join(",");
            s = s.substring(0, s.length - 1);
            console.log(s);
            $('#job_tags_input').val(s);
        },
        onDelete: function(tag) { 
            /*$("#job_tags_input").val( $("#job_tags li").map(function(){
                return $(this).text();
            }).get().join(", "));*/
            var array = $("#job_tags_input").val().split(",");
            array = $.grep(array, function(value, i) {
                return ( value.indexOf(tag) == 0 );
            });
            array = array.join(",");
            console.log(array);
            $('#job_tags_input').val(array);
        }

    });
}
Ian Nelson
  • 57,123
  • 20
  • 76
  • 103
Udders
  • 6,914
  • 24
  • 102
  • 194

3 Answers3

0

You can splice the item first:

array.splice(array.indexOf("C"), 1); // remove one item at the position of "C"

Then join the elements together and update the textbox:

$("#job_tags_input").val(array.join()); // uses "," by default

However, you'd be better off splitting on ", " since the space is part of the delimiter.

pimvdb
  • 151,816
  • 78
  • 307
  • 352