-1

I have a text input where I get the input and use it. I have:

$(myinput).on('input', function() {
 $(somediv).append($(this).val());
});

I would like to keep using the append function, but the problem is on every input, the entire input val() is being appended. So when I click 'a', its adding 'a', but when I click 'b' after a, it appends 'ab' not 'b'.

is there a way to only get the input of the most recent .input event without clearing out the input box?

5
  • I would like to keep using the append function? why? Commented Mar 6, 2015 at 16:01
  • You want to use .append, but you don't want to append? Commented Mar 6, 2015 at 16:01
  • @codehx I was using $(somediv).text(); instead of append, but that was screwing up some other html I had inside the div Commented Mar 6, 2015 at 16:12
  • Then put an element with id ( say <span id = "replaceable"></span>) for the replaceable content. Then you freely use $("#replaceable").text("your text"), if you want to do it this way I can post an answer. Commented Mar 6, 2015 at 16:21
  • @codehx yea I guess that works Commented Mar 6, 2015 at 16:50

4 Answers 4

2

you could use .text() instead of .append(). This will set the whole text, not just append it.

$(somediv).text($(this).val());

Or you could use the last char of your string.

$(somediv).text($(this).val().slice(-1)); See: how to get the last character of a string?

Sign up to request clarification or add additional context in comments.

Comments

1

I am assuming that you want to use append because there is other content in somediv that you don't want to lose. If that is the case, you can create a sub-element to receive the text, append it just once, then change its contents when the input field changes:

var receiver = $('span');
$(somediv).append(receiver);

$(myinput).on('input', function() {
 receiver.html($(this).val());
});

Comments

0
$("#myinput").on('input', function() {
   $("#somewhere").val("");
   setTimout(function() {
       $("#somewhere").append($(this).val());
   },10);
});

or

$("#myinput").focusout(function() {
   $("#somewhere").val("");
   setTimout(function() {
       $("#somewhere").append($(this).val());
   },10);
});

the timeout is for doing things without overlapping. You can try also without timoeout

Comments

0

You could also bind to the keyup event:

$(document).on('keyup', '#inputID', function(e){
     var key = String.fromCharCode(e.which);
    $('div').append(key);
});

jsFiddle Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.