The structure is trivial:

<div class="data_form"> <div class="newprog"> Тот который получит текст инпута </div> <div> <input>Тот который я изменяю </div> </div> 

As I just did not try to turn to the right block, for example:

 $(".data_form:has(".$(this).").newprog").text($(this).val()); 

The remaining options are embarrassing to show ... What am I doing wrong?

    3 answers 3

    Try this:

     $("div.data_form input").on("keyup", function(e){ $(e.target).closest(".data_form").find(".newprog").text($(this).val()); }); 

    Words can be described as follows: in the event of an input element, we are looking for the first parent element with the data_form class and from it downwards we are looking for an element with the newprog class. More about event.target here .

    Sample code .


    If you add blocks using a script, then this example will not work. In this case, you need to "wrap" the blocks, for example in a div and have an event handler on it:

     $("button").on("click", function() { $(".data_form:first").clone().appendTo(".container"); }); $("div.container").on("keyup", "input", function(e) { $(e.target).closest(".data_form").find(".newprog").text($(this).val()); e.preventDefault(); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Add new container</button> <div class="container"> <div class="data_form"> <div class="newprog">Текст инпута 1</div> <div> <input /> </div> </div> </div> 

    JSFiddle example

    • @Levelleor It all depends on your markup. If it does not change, it is quite a working option. Otherwise, the given example is preferable, since not bound to input nesting. Corrected the answer. - XelaNimed September
    • Okay, thanks so much for the help and advice! I read about delegate () and everything turned out. - Telion

    Did you .find() ?

     var input = $('.data_form').find('input'), box = $('.data_form').find('.newprog'); input.on('keypress', function(){ console.log(input.val()); box.text(input.val()); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="data_form"> <div class="newprog"> Тот который получит текст инпута </div> <div> <input>Тот который я изменяю </div> </div> 

    • Maybe something like: $(".data_form.newprog").find(this).text($(this).val()); ? The point is that on the page of such blocks there can be infinitely many, and therefore the task of finding the variable title of this particular block in which the input'a change occurs. Because the task is to find it through this ... By the way, this option does nothing at all and does not give an error. - Telion
     $(".prog_name").on('input', function() { $(this).parent().parent('.data_form').children('.newprog').text($(this).val()); }); 

    Found myself such an answer. Go back up to 2 parents and select a child with the specified class. It does not work for blocks created by the script for some reason ...