charlie
charlie

Reputation: 481

Prepend value to textarea

I have created this JQuery code to prepend a textarea input

$(document).ready(function() {
    var data = <?php echo $data; ?>;

    $('#standard_response').on('change', function() {
        var sequence = $(this).val();
        //Check each object in the data array
        $.each(data, function( index, obj ) {
            if(obj.sequence === sequence) {
                $('#description').prepend( obj.response );
            }
        });
        //$('#standard_response').select2('val', '');
    });
});

but it only works when the textarea is empty.

i want it to add the text at the end of the textarea where the cursor was left

i have also tried:

$('#description').text( $('#description').text() + obj.response );

$('#description').text( $('#description').val() + obj.response );

but neither of these work either

Upvotes: 0

Views: 784

Answers (3)

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

Use val

var value = $('#description').val();
$('#description').val(value + obj.response );

Upvotes: 2

Phuong Nguyen
Phuong Nguyen

Reputation: 121

Try:

$('#description').val( $('#description').val() + obj.response );

Upvotes: 3

Rory McCrossan
Rory McCrossan

Reputation: 337714

Assuming that #description is the textarea element, you should use val() to set its value. You can provide a function to the method to prepend the easily append new value. Try this:

if (obj.sequence === sequence) {
    $('#description').val(function(i, v) {
        return obj.response + v;
    });
}

Upvotes: 2

Related Questions