1

In a web page we have an input type text:

<input id="bar" type="text" />

I want to insert before another input element before the above element:

var input = $('<input type="text" value="foo" id="ciccia" />')
input.insertBefore($('#bar'))

And add a simple behavior:

input.on('keyup', function(){
    console.log(input.attr('value'));
})

console.log always get "foo" string


If I change

 var input = $('<input type="text" value="foo" id="ciccia" />')

to

 var input = $('<input type="text" value="bar" id="ciccia" />')

console.log always get "bar" string.


What's wrong with DOM? Why I cannot read the real value of text input?

2 Answers 2

4

Try to use .val() to retrieve the text box value, since .attr('value') will always return the value which was set in the beginning.

input.on('keyup', function(){
    console.log(input.val());
});

or simply use this.value instead of input.val()

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

Comments

1

attr will always return the value which was initially set. You need to use .value property

Use

input.on('keyup', function(){
    console.log(this.value);
})

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.