1

I've a form with an empty input#tags. I have a p#list_tags with few span.keyword. When I click a .keyword, its text append to input.val() But I can't remove its text from val() if I click on it again. My code :

$("p#list_tags span.keyword").click(function() {
    var tag = $(this).text();
    var tags = $("#tags").val();

    if($(this).hasClass('selected_tag')) {
        $(this).removeClass('selected_tag');
        // Here, I don't know what to do... I've tried this, but...
        // $("#tags").remove(":contains('" + tag + "')");
    }
    else {
        $("#tags").val(tags + ' ' + tag);
        $(this).addClass('selected_tag');
    }
});

1 Answer 1

1

Try this

$("p#list_tags span.keyword").click(function() {
    var tag = $(this).text();
    var tags = $("#tags").val();

    if($(this).hasClass('selected_tag')) {
        $(this).removeClass('selected_tag');

        //if that tag is last one, we need to append space before tag
        var res = tags.split(" "); 
        var replaceString = "";
        if(res[res.length-1] == tag){
          replaceString = " " + tag;
        }else{
          replaceString = tag + " ";
        }

        $("#tags").val(tags.replace(replaceString, "")); // Replace with empty value
    }
    else {
        $("#tags").val(tags + ' ' + tag);
        $(this).addClass('selected_tag');
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.