Thursday 15 July 2010

Edit on site with Javascript -



Edit on site with Javascript -

i have school assignment love have on site edit admin panel. coded cant work properly, every time double click in 1 , out replaces value previous value.

<script type="text/javascript"> $(function() { var bound = $("p").bind("dblclick", function(event) { event.stoppropagation(); var currentele = $(this); var value = $(this).html(); edit(currentele, value); }); }); function edit(currentele, value) { $(currentele).html('<input class="tedit" type="text" value="' + value + '" />'); $(".tedit").focus(); $(".tedit").keyup(function(event) { if (event.keycode == 13) { currentele.parent('p').html($(this).val().trim()); } }); $(document).click(function() { var value1234 = $(".tedit").val().trim(); $("p").removeclass(); currentele.html(value1234); }); } </script>

here jsfiddle http://jsfiddle.net/x6e16d3n/3/

the issue because every time edit create new click handler attached document has reference current element @ time of creation.

this handler still active when editing object , still has reference old element (look closures understand why) taking value add together p ever .tedit on screen in end updated same text.

one quick soloution take click handler out of dit function , declare once, check if edit on screen , if create edits parent html equal value of input box

$(function () { var bound = $("p").bind("dblclick", function (event) { event.stoppropagation(); var currentele = $(this); var value = $(this).html(); edit(currentele, value); }); }); function edit(currentele, value) { $(currentele).html('<input class="tedit" type="text" value="' + value + '" />'); $(".tedit").focus(); $(".tedit").keyup(function (event) { if (event.keycode == 13) { currentele.parent('p').html($(this).val().trim()); } }); } $(document).click(function () { if ($(".tedit").length) { var value1234 = $(".tedit").val().trim(); $("p").removeclass(); $(".tedit").parent().html(value1234); } });

example fiddle http://jsfiddle.net/x6e16d3n/11/

javascript

No comments:

Post a Comment