0

I'm trying to add multiple strings to an input field via multiple buttons. The problem is, is that every time I click a new button it replaces/overrides the previous insert so I cant add strings only replace.

Would also like to remove the string if the same button is re-clicked

Please see code below and fiddle - http://jsfiddle.net/2khzX/

 <input type="text" id="text" style="width: 450px;" />
 <br />
 <button>Hello</button>
 <button>Yes</button>
 <button>No</button>
 <button>Maybe</button>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">    </script>
 <script>
  $("button").on('click', function() {
    var text = $(this).text();
    $("input").val(text + ',');
  });
 </script>

2 Answers 2

1

First, get the value from the existing input.

Then check to see if the current text already exists. If so, get rid of it.

Then append the current text onto the end.

$("button").on('click', function() {
    var text = $(this).text() +',';
    $('input').val(function(_, val) {
        if (val.match(text)) {
            return val.replace(text, '');
        }
        return val + text;
    });
});

jsFiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Close, but dont want the word to appear again if reclicked
@Kulerbox: Ah, I misunderstood that part. Take another look. Should be working ask you expect now.
0

Add the value that is already in the input as well, otherwise it just replaces whatever is there with the new value

$("button").on('click', function() {
    var text = $(this).text();

    $("input").val(function(_, val) {
        var arr = val.split(','),
            pos = $.inArray(text, arr);

        pos != -1 ? arr.splice(pos, 1) : arr.push(text);

        return arr.filter(function(n) {
            return n.trim().length
        }).join(',');
    });
});

FIDDLE

2 Comments

Thanks, works great, but how do you remove the value if clicked again?
@Kulerbox - Ah, okay! Updated the answer with that as well.

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.