Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding additional value to existing value of an inputfield on click - jQuery

Tags:

jquery

click

i got this inputfield with tag buttons

<input id="demooutput" type="text" size="15" value="My Text" name="demo" />
<span class="demooutput">
    <a href="#" class="button orange"> A</a>
    <a href="#" class="button orange"> B</a>
    <a href="#" class="button orange"> C</a>
    <a href="#" class="button orange"> D</a>
    <a href="#" class="button orange"> E</a>        
</span>

with this jQuery code i add the values to the input

$('.demooutput a').click(function(){
    $('#demooutput').val($(this).html());
    return false;
});

but i clear my existing value with every click on the button

i want to add the value from the button additionally to the existing value from input

Example who i want it

My Text A (by click on A)
My Text A B (by click on A and B)
My Text B C E (by click on B, C and E)
and so on..


See a Demo on JSFIDDLE

like image 492
bernte Avatar asked Feb 04 '26 01:02

bernte


2 Answers

$('#demooutput').val($('#demooutput').val() + $(this).html());

like image 57
Hamed Khosravi Avatar answered Feb 05 '26 17:02

Hamed Khosravi


Try this:

$('.demooutput a').click(function(){
    var values = $('#demooutput').val().split(' ');
    values.push($(this).html());
    $('#demooutput').val(values.join(' '));
    return false;
});

DEMO

Or just simply:

$('.demooutput a').click(function(){
    $('#demooutput').val($('#demooutput').val() + ' '+ $(this).html());
    return false;
});

DEMO

The first approach is recommended in some cases though, as it separates the logic clearly. For example: if you need to toggle the text (click 'A' and then click 'A' again to hide 'A', just to remove 'A' from the array and join)

like image 40
Khanh TO Avatar answered Feb 05 '26 18:02

Khanh TO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!