Luntegg
Luntegg

Reputation: 2556

How catch event from "event-changing" element?

I have two <textarea></textarea> and one <div></div>.

If I change text in #first textarea, this text copied in #second textarea. How I may catch event, that if text in #second textarea changed, I change text in div #needle? Which event?

Events change keyup paste input propertychange don't work..

I don't want to use compulsory event $('#second').change() in first event..

<textarea id="first"></textarea>
<textarea id="second"></textarea>
<div id="needle"></div>

<script>
    $('#first').keyup(function(){
         $('#second').val($(this).val());   
    });

    $(document).on('change keyup paste input propertychange', '#second', function(){
        $('#needle').text($(this).val());
    });
</script>

JSFiddle

Upvotes: 0

Views: 112

Answers (4)

Luntegg
Luntegg

Reputation: 2556

This event is uncreated in jquery..

Upvotes: 0

Ionică Bizău
Ionică Bizău

Reputation: 113485

input event is enough.

I would recommend you to create a function like changeText that you call when input even is triggered in the second textarea and when you update the text in it.

$('#first').on("input", function(){
    changeText.call(
      $('#second').val( // <- You update the second textarea value
         $(this).val()  //    with the text from the first textarea
      )                 // <- This will return the second textarea jQuery object
    );
});

$(document).on('input', '#second', changeText);

function changeText() {
    // here `this` will be the second textarea jQuery object 
    $('#needle').text($(this).val());
}

JSFIDDLE

Upvotes: 1

Krishjs
Krishjs

Reputation: 368

You could use a named function instead of using anonymous function.

function onChangeSecond()
{
 $('#needle').text($(this).val());
} 

you can use onChageSecond() in keyUp Events of First and Second Textarea.

Upvotes: 0

Mostafa Talebi
Mostafa Talebi

Reputation: 9183

you should use "change" event:

$('#second').on('change', function(){
 $('needle').append($(this).val()); // this appends the value 
});

Note that we are using append() method. If we use html() or text(), we literally override the #needle value on each change occurrence which probably look strange and unsual (and unusable perhaps).

Upvotes: 0

Related Questions