Question

I'd like to know how to append link values to an input box. But I can't figure out how to append a new link value to the old one, separated by a space [Fiddle].

<input id="a_input_id" type="text">
<a href="" class="special_field_link">@ABC<a>
<a href="" class="special_field_link">@DEF<a>

<script>
$(function(){
    $('.special_field_link').live('click', function()
 {

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

          return false;


 });
});

Should I use something like:

var cur_val = $('#a_input_id').val($(this).html() + '');
if(cur_val)
  $('#a_input_id').val(cur_val + "," + new_val);
else
  $('#a_input_id').val(new_val);

Your help would be appreciate.

Was it helpful?

Solution

You can use like this,

 $('.special_field_link').click(function (e) {
    e.preventDefault();
    $('#a_input_id').val($('#a_input_id').val()+" "+$(this).html());
});

Use event.preventDefault() to prevent the default click event of anchor. In each click you need to get the current input value, if you want to retain those. In your code, it was overwriting the old with the new values.

Fiddle

OTHER TIPS

If you want to append the value, you could do:

var input =  $('#a_input_id');                        
input.val(input.val() + $(this).html());                 

And note .live is deprecated, you'd better use .on instead if you switch to a new version of jQuery.

THE DEMO.

You could go with:

http://fiddle.jshell.net/s8nUh/149/

$(function()
 {
     $('.special_field_link').live('click', function()
     {
        var original = $('#a_input_id').val();
        var val = original + ',' + $(this).html();
        val = val.replace(/(^,)|(,$)/g, "");
        $('#a_input_id').val(val);     
        return false;                                 
     });
});
$(function(){
    $('.special_field_link').live('click', function()
    {

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

    return false;                              
    });
});

To use best practices, its better to cache jquery object for anchor and also avoid using return false.

$(function(){
    var txt$ = $('#a_input_id');

    $('.special_field_link').live('click', function()
    {
        txt$.val(txt$.val() + $(this).html());    
        event.preventDefault();                       
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top