Mangala Edirisinghe Mangala Edirisinghe - 1 month ago 10
jQuery Question

How to append text to text box value using jQuery?

I need append - to the present text box value without replacing present text. I tried with this code.

if(len.length==4){
$("-").appendTo("#date").val();
}


but it failed.

Answer

Though you got several(but not all) correct answers, I want to show another way to do it:

$('#date').val(function(index, value) {
    return value + '-';
});‚Äč

.val( function(index, value) )

function(index, value)A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

source

If you don't want to use function for doing it, use this:

var $date = $('#date');
$date.val($date.val() + '-');