Adding text and editing text for a div button click event

I work with div and jquery elements. I can create a new div and add text through a button click event. Each div created has a draggable property thanks to the jqueryui plugin. In addition, I can remove individual divs through the onclick event. But I ran into this problem: since I can add text to the div, click the button. How to edit the text of a previously created div? JSFIDDLE

Jquery

/** Remove newly created div **/ $(".remove").click(function(){ $(".draggable").remove(); }); var z = 1; $('#button').click(function (e) { /** Make div draggable **/ $('<div />', { class: 'draggable ui-widget-content', html: '<span class="close">[X]</span><span class="text">' + $('textarea').val() + '</span>', appendTo: '.middle-side', draggable: { containment: 'parent', start: function( event, ui ) { $(this).css('z-index', ++z); } } }).addClass('placement'); /** Contain draggable div **/ $('.middle-side').parent().mousemove(function(e){ var offset = $(this).offset(); var relX = e.pageX - offset.left; var relY = e.pageY - offset.top; $('.placement').css({'top': relY + 30,'left': relX + 10, 'position': 'absolute'}); }) }); $('body').on('click', '.draggable .close', function () { $(this).closest('.draggable').remove(); }); 

HTML

 <textarea rows="4" cols="50" placeholder="Enter Text Here!"></textarea> <br/> <input type="button" id="button" value="Add Div with Text" /> <br/> <div> <div class="middle-side empty"></div> </div> 
0
source share
2 answers

How are you already using jQuery-ui - how about using a dialog?

Here is an example (non-stationary). As Geraud Mathe suggested that I used the dblclick() event:

JSFiddle | Dialog document

 theDivJustAdded.dblclick(function() { var divElem = $(this); dialog = $( "#dialog-form" ).dialog({ height: 300, width: 350, modal: true, buttons: { "Save": function() { divElem.find('.text').text($( "#dialog-form input" ).val()); dialog.dialog( "close" ); }, Cancel: function() { dialog.dialog( "close" ); } } }); } ); 
+2
source

I would add a double-click event listener to each div added, then when the event is fired, you will get the div text and add it inside the text box, change the button text from “Add Div with Text” to “Refresh div content” when the user clicks the button, you replace the text of the associated div with the one inside the text field

+1
source

Source: https://habr.com/ru/post/974605/


All Articles