Roel
Roel

Reputation: 1472

jQuery onChange add value of field to HTML

I want to print the value of a input field real-time to a DIV.

Right now I have got this:

        $("#page_name").change(function () {

            var new_val = $("#page_name").val();

            $("#page_url").html(new_val);

        });

It doesn't work, obviously. Anyone got a suggestion?

Thanks!

Upvotes: 1

Views: 1651

Answers (3)

Murphy
Murphy

Reputation: 131

As pointed out 'change' only occurs when the element loses focus. An alternative to binding it to the keypress event would be binding it to the "input" event.

$('#page_name').bind('input', function(e){
    var output = e.target.value;
    $('#page_url').text(output);
});

http://jsfiddle.net/xY7Q6/

The problem with keypress is that it does not work on copy&paste text.

The input event is pretty much what everybody expects 'change' to be (o: I think this event is pretty new (HTML5?), older browsers may not get that one.

Upvotes: 3

Cyril Gupta
Cyril Gupta

Reputation: 13723

Actually it will work, but only when you move the cursor out of the input box, because change fires when the focus is lost.

What you need is keypress. The code is just the same as yours

 $("#page_name").keypress(function () {
            var new_val = $("#page_name").val();
            $("#page_url").html(new_val);
});

test it here

http://jsfiddle.net/y3zpP/

Upvotes: 0

issa marie tseng
issa marie tseng

Reputation: 3234

That should actually work. My best guess is this:

  1. Check your selectors, perhaps. Also, you can use $(this) instead of selecting #page_name that second time.
  2. Change doesn't always fire as often as you might think it should. Try binding the event to keyup instead.
  3. Also, it's probably a bad idea to .html() the node. You'll probably want to .text() it to be safe.

Upvotes: 3

Related Questions