开发者

jQuery onChange add value of field to HTML

开发者 https://www.devze.com 2023-02-28 09:16 出处:网络
I want to print the value of a 开发者_开发技巧input field real-time to a DIV. Right now I have got this:

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!


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.


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.


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消