Mangala Edirisinghe
Mangala Edirisinghe

Reputation: 1111

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.

Upvotes: 7

Views: 32387

Answers (6)

Hugh Seagraves
Hugh Seagraves

Reputation: 594

I was just doing this. I used .append(myValue); here I'm looping through an Ajax result set:

        $.each(result, function (i, obj) {
            $.each(obj, function (i, item) {
                $('#txtValueList').append(item);
            })
        })

Upvotes: 0

gdoron
gdoron

Reputation: 150273

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() + '-');

Upvotes: 16

KoolKabin
KoolKabin

Reputation: 17683

try:

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

Upvotes: 2

Florian Margaine
Florian Margaine

Reputation: 60797

The most elegant way I've found includes not using jQuery so much.

if ( len.length === 4 ) {
    var date = $( '#date' )[0] // faster to write than "document.getElementById( 'date' )"
    date.value += '-'
}

Fiddle: http://jsfiddle.net/Ralt/T9mUT/3/

Upvotes: 2

Warren Sergent
Warren Sergent

Reputation: 2597

jQuery('#date').val(jQuery('#date').val() + '-');

Upvotes: 2

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14737

You've got to retrieve the current value, and append to that.

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

Upvotes: 5

Related Questions