0

I'm experiencing this trouble with jQuery and attr() function.

Take a look:

one <input id='one' type="text"><br>
two <input id='two' type="text">

<script>
$('#one').on('input',
             function(){
                 var result = 'test'
                 $('#two').attr('value',result);
             }
            );
</script>

This is the trouble:

  1. I type something in the 'one' input;
  2. the 'test' text was correctly inserted in the 'two' input.
  3. Now I edit the content of the 'two' input.
  4. Now if I type something new in the 'one' input , the 'two' input content isn't replaced with the 'test' text ! Why ?! How can I fix it ?

P.S. See the live code here http://jsfiddle.net/5XQJj/4/

3 Answers 3

2

Use .val() to set input values:

http://jsfiddle.net/dh23j/

$('#two').val(result);

Often, setting element attributes won't update more than once. You need to update their properties instead using .prop or using functions intended for the purpose, like .val().

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

4 Comments

great ! but If I need to update the value property also, sould I do something like $('#two').val(result).attr('value',result) ??
No, .val() should do that for you. I believe that's probably what happens behind the scenes.
in firebug i cannot see this.. are you sure ?
Fairly. What are you looking at? Do you need to refresh a watch maybe?
0

Try .prop()

$('#one').on('input', function () {
    var result = 'test'
    $('#two').prop('value', result);
});

fiddle Demo

Read .prop() vs .attr()


Better use .val()

fiddle Demo

$('#two').val(result);

Comments

0

you should use .val() rather than .attr or .prop

updated JSfiddle: http://jsfiddle.net/5XQJj/6/

$('#one').on('change', function () {
    var result = 'test'
    $('#two').val(result);
});

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.