Question

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/

Was it helpful?

Solution

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().

OTHER TIPS

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);

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);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top