When bbcode() called, the function only works in the textarea where it was called the first time.
How to get the id current item every time? Or maybe you can somehow clear the id ?

Html code:

 <ul> <li class="item" id="item-21351"> <a href="javascript:void(0)" class="edit">Редактирование</a> <div class="content"> <div class="describe"></div> </div> </li> <li class="item" id="item-23512"> <a href="javascript:void(0)" class="edit">Редактирование</a> <div class="content"> <div class="describe"></div> </div> </li> <li class="item" id="item-12351""> <a href="javascript:void(0)" class="edit">Редактирование</a> <div class="content"> <div class="describe"></div> </div> </li> </ul> 

Clicking on edit calls the form:

 <form method="post"> <div class="btn" onclick="bbcode('redit','[tag]','[/tag]')" >[tag]</div> <textarea name="redit" class="redit" id="redit"></textarea> </form> 

bbcode replaces selected text

 <script> function bbcode(elementID, openTag, closeTag){ var tarea = document.getElementById( elementID ); var val = tarea.value; var s = tarea.selectionStart; var e = tarea.selectionEnd; tarea.value = val.substring( 0, s ) + openTag + val.substring( s, e ) + closeTag + val.substring( e, val.length ); } </script> 
  • Do you have several textarea with the same id? It won't work like that - sercxjo
  • @sercxjo then they and Id so that they are different, in this case it’s better to bind to the class, for example "redit" and then it will work everywhere - Dmitry

2 answers 2

So it should work, redo it for yourself if something is wrong

 $('.edit').click(function() { var desc = $(this).parent().find('.describe').html(); var desc_id = $(this).parent().attr('id'); $('.redit').val(desc).attr('data-desc-id', desc_id).parent().show(); }); $('.btn').click(function() { var desc = $('.redit').val(); console.log(desc); var desc_id = $('.redit').attr('data-desc-id'); $('#' + desc_id).find('.describe').html(desc); $('.redit').val('').parent().hide(); }); 
 <ul> <li class="item" id="item-21351"> <a href="javascript:void(0)" class="edit">Редактирование</a> <div class="content"> <div class="describe">чтото1</div> </div> </li> <li class="item" id="item-23512"> <a href="javascript:void(0)" class="edit">Редактирование</a> <div class="content"> <div class="describe">чтото2</div> </div> </li> <li class="item" id="item-12351"> <a href="javascript:void(0)" class="edit ">Редактирование</a> <div class="content "> <div class="describe">чтото3</div> </div> </li> </ul> <form method="post " style='display:none;'> <input type='text' name="redit" class="redit" id="redit"> <div class="btn ">save</div> </form> 

    In the bbcode function bbcode first argument instead of 'redit' pass this .

    To search the input area, it is better to use relative addressing, rather than id:

     function bbcode(element, openTag, closeTag) { var tarea = $(element).closest('form').find('textarea.redit'); ... }