Greetings. The task is as follows: There are several N-th number of identical blocks of approximately the following structure:

<div class="wrap"> <div class="wrap-c"> <p class="name">NAME</p> </div> <form> <input type="text"> <input type="tel"> <input type="submit"> </form></div> 

I repeat, the structure is approximate. There are several blocks. It is necessary that the text from the P tag automatically fills the text box of the form in its block. This field will not be visible to a person at all (hidden) - he entered, and the js / jquery script immediately filled the field with an automatic machine. The field in the form may also be a different number, so perhaps it is better to hang on a class or id any.

    2 answers 2

    If just a text field

     $('input[type="text"]').val($('p.name').text()); 

    If the forms in your block

     $('p').each(function(){ $(this).siblings('form').find('input[type="text"]').val($(this).text()); }); 

    If the forms in the block of one of the parents

     $('p').each(function(){ $(this).parents('.wrapper').siblings('form').find('input[type="text"]').val($(this).text()); }); 
    • The first option is not suitable, because such use in each field gets the text from all paragraphs. But the second option is already working selectively, but there is a problem - the level of nesting in a block for a paragraph and a form is different, and siblings works, only at the same level. Is there another way, for example, to specify the class of the main unit and that the work should be carried out inside this unit, rather than nesting? - Aaron
    • If as in your example, you just need to add .parent (). What would be $ (this) .parent (). Siblings ('form'). Find ('input [type = "text"]') Then the form will be searched next with the parent of the paragraph - Andy
    • And if the depth of the nesting and the paragraph and the form is large and the only common - the outermost block is a wrapper, how to be? In the first post I’m just an example, I can’t give you the reality (I’m not ready yet), but everything is obviously more “tree-like” - Aaron
    • In this case, you should use .parents (selector) api.jquery.com/parents This will be something like $ (this) .parents ('. Main-wrapper'). Siblings ('form'). Find ('input [type = "text"] ') - Andy
    • Excuse me, are you sure that there is no error in the code with parents (selector)? just this option does not work at all. - Aaron

    To the field to be filled in, set the value equal to the text of the corresponding paragraph.

     $('input.name').val($('p.name').text()); 
    • This option is suitable only if there is one text field and one paragraph on the page that you want to use. And there are a lot of blocks that should work independently of each other in this scenario on the page. - Aaron