Search code examples
javascriptjqueryregextextinput

jQuery Remove part of a value from an Input box


If you see my JSFiddle (bottom of post), my main problem occurs when I delete the tags from the input box on the left, they aren't removed from the box on the right, and I'm not sure how to go about it.

Basically I need to remove the part of a value from an input box that is present after the second to last comma.

My problem in more detail:

I am creating a tag form in the style of stack overflow.

At the moment I have 2 input boxes. The one on the left is the one users will use. When they add tags to this box, the tags are styled in span tags so it looks user friendly.

At the same time, the tags are also added to the input box on the right (which i will have hidden). The box on the right must have each tag separated by commas, as this is the format necessary for when the form gets submitted.

I have got so far, but the problem is when I delete the tags from the first box, they aren't removed from the box on the right..I'm unsure how to do it. Maybe I will have to match the strings?

Code:

Html:

<span id="tags"></span><input id="enterTag" type="text" />

<input id="hiddenbox" type="text"/>

JS:

$('#enterTag').keydown(function(event) {
    var tag = $(this).val();
    // 188 is comma, 13 is enter
    if (event.which === 188 || event.which === 13) {
        if (tag) {
            $('#tags').append('<span>' + tag + '</span>');
            $(this).val('');
           $('#hiddenbox').val($('#hiddenbox').val() + tag+', ');
        }
        event.preventDefault();
    }
    // 8 is backspace
    else if (event.which == 8) {
        if (!tag) {
            $('#tags span:last').remove();
            event.preventDefault();
        }
    }
});​

JSFiddle: http://jsfiddle.net/greylien/pUfNu/9/


Solution

  • try

    $('#enterTag').keydown(function(event) {
        var tag = $(this).val();
        // 188 is comma, 13 is enter
        if (event.which === 188 || event.which === 13) {
            if (tag) {
                $('#tags').append('<span>' + tag + '</span>');
                $(this).val('');
               $('#hiddenbox').val($('#hiddenbox').val() + tag+', ');
            }
            event.preventDefault();
        }
        // 8 is backspace
        else if (event.which == 8) {
            if (!tag) {
                $('#tags span:last').remove();
                var str = $('#hiddenbox').val();
                var str_a = str.split(',');
                str_a.pop();
                str_a.pop();
                if(str_a.length>0){
                    var str_val = str_a.join(',')+', ';
                }else{
                    var str_val = '';
                }
                $('#hiddenbox').val(str_val );
                event.preventDefault();
            }
        }
    });​
    

    js fidle :

    http://jsfiddle.net/pUfNu/11/