2

I would like to use jquery to append text onto what the user has typed in a text box, while the user is typing.

Say I wanted to append " is a hat" to the end of what the user typed.

Lets say the user starts typing "My Friend" into the field.

As they type the box will read:

M -> M is a hat
y -> My is a hat
  -> My  is a hat
F -> My F is a hat
r -> My Fr is a hat
...

I started writing a function for the keypress event, but then I realized that I would end up with something like

M -> M is a hat
y -> M is a haty is a hat
...

So what I want to know is how I should

  1. Replace the old suffix
  2. Place the cursor back to where the user was typing
  3. Make sure they only are able to type before the suffix, so they they can't edit the suffix

3 Answers 3

3

You can append to a span like so:

var phrase = " is a hat";
$("#idOfInput").keydown(function() {
    $("#idOfSpan").html(this.value + phrase);
});
Sign up to request clarification or add additional context in comments.

Comments

3

You can try this

JS

$("input").keyup(function() {
    $(".dynamic").html(this.value);
});

HTML

<input type="text" />
<div>
    <span class="dynamic"></span>
    <span class="static"> is a hat </span>
</div>

Check Fiddle

You will basically targeting the span that holds the dynamic text and render the html based on the keyup event.

1 Comment

I took tyme's just because of the difference of how he did it, but +1 for the fiddle.
0
this following example work perfectly .  
 **html**

    <input type="text" id="text"/>
    <p><span id="app"></span>
    <span>this is a hat</span>
    <p>

    **script**
    ----------
    $("#text").keyup(function(){
        $("#app").text($("input").val());
    });

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.