Alon Shmiel
Alon Shmiel

Reputation: 7121

enter value of input to the html, not the dom

I have an input in my html file (attribute id is: imgName).

while the user enters some text to this input, it's inserted to the DOM.

I want it to be inserted to the html.

so I try to do this thing:

$(document).keydown(function (e) {
    if (e.target.id == "imgName") {
        // get the char and create text node
        var text = document.createTextNode(String.fromCharCode(e.which));
        // insert it to the input
        e.target.appendChild(text);
    }
});

but it does nothing..

any help appreciated!

Upvotes: 0

Views: 65

Answers (2)

Manuel Richarz
Manuel Richarz

Reputation: 1926

You've done something wrong:

  1. Your are listening for an input-event on your complete document, but your input will only be on your input-field. so you need: $('#imgName').keydown...

  2. You are using jQuery... so, use it to do this stuff is easier.

  3. Your condition is not needed.

try this:

$('body').append(String.fromCharCode(e.which));

DEMO

Upvotes: 1

adeneo
adeneo

Reputation: 318302

You can't append something to an input, it's a self closing element that has no content, and to get the proper result from String.fromCharCode you should be using the keypress event

$('#imgName').on('keypress', function (e) {
    var text = document.createTextNode(String.fromCharCode(e.which));
    document.body.appendChild(text);
});

FIDDLE

Upvotes: 1

Related Questions