Reputation: 1696
Ok when i click on an button with the class "allas" i want that jquery appends the text of the button to my input with the id "inputbox". So far all works good:
$(document).ready(function() {
$('.allas').click(function() {
$('#inputbox').val($(this).text());
});
});
But first problem is that my code always replaces the input val, when i click on another button with the class "allas". I want that jquery adds the value seperated by an ;
And "i think the more difficult part" i want an undo function, that when the user clicks again on an button that he yet has pressed the value of the button should be delted from the input!
I hope you understand me? Thanks for help!
Upvotes: 0
Views: 142
Reputation: 550
Try keeping a history of the value.
HTML
<input type="text" id="inputbox" value=""><br>
<button class="allas">one</button>
<button class="allas">two</button>
<button class="allas">three</button>
<button class="undo">undo</button>
Document Ready
$(function()
{
var history = [''];
$('.allas').click(function()
{
var $this = $(this);
var $inputbox = $('#inputbox');
var value = $inputbox.val() + $(this).text();
history.push(value)
$inputbox.val(value);
});
$('.undo').click(function()
{
history.pop();
var lastIndex = history.length - 1;
var $inputbox = $('#inputbox');
var value = history[lastIndex];
$inputbox.val(value);
});
});
Upvotes: 1
Reputation: 48972
A simple way to do it:
var inputValues = [];
$(document).ready(function() {
$('.allas').click(function() {
var inputValue = $(this).text();
var index = inputValues.indexOf(inputValue);
if (index >= 0){
inputValues.splice(index,1);
}
else{
inputValues.push(inputValue);
}
$('#inputbox').val(inputValues.join(";"));
});
});
If you don't want to store global variable, try this:
$(document).ready(function() {
$('.allas').click(function() {
var inputValues = [];
if ($('#inputbox').val() != "")
{
inputValues = $('#inputbox').val().split(";");
}
var inputValue = $(this).text();
var index = inputValues.indexOf(inputValue);
if (index >= 0){
inputValues.splice(index,1);
}
else{
inputValues.push(inputValue);
}
$('#inputbox').val(inputValues.join(";"));
});
});
Upvotes: 1