I’ve written a rudimentary text editor for my page. Any tag with the .edit class can be clicked by a logged in user and a form appears with the text in the textarea field to be edited in addition to unbinding the ‘click’. Upon submit the function performs a post and updates the database via a ColdFusion component and reloads the page to reflect the changes made. Works great (thanks in no small part to the Stackoverflow community and Ray Camden).
I created a ‘cancel’ function that clears the form field (because it’s reusable) and re-binds teh ‘click’. The trouble is, I see in firebug that if I click some text, cancel, click some other text and then click submit my code performs two posts – one for the cancelled click and one for the real thing.
What do I need to do to kill that first aborted effort?
Here’s the code:
$(document).ready(function() {
$('#cancelEdit').click(rebinder);
$('.edit').click(texteditor);
function texteditor(){
var theName = $(this).attr('name');
var textToEdit = $(this).html();
var theParentID = $(this).closest('div').attr('id');
var theTag = this.tagName.toLowerCase();
var theID = theName.split("-")[1];
var gateway = ("<cfoutput>#URL.page#</cfoutput>");
var fieldDims = [$(this).css('width'), $(this).css('height')];
$('#theText').attr('value', textToEdit );
$('#theText').css('height', fieldDims[1]);
$('#theText').css('width', fieldDims[0]);
$('.edit').unbind('click');
$('#texteditform').submit(function(e){
//stop the form submission
e.preventDefault()
var newText = $('#theText').val();
//CFC
$.post("cfc/engine.cfc?method=updateText&returnformat=json",
{text:newText, field:theID, gateway_id:gateway},
function(res) {
//Handle the result
if(res.trim() == "true") {
$('#theText').attr('value', '');
location.reload();
//$('.edit').bind('click');
} else {
alert("Didn't Work");
}
});
});
};
function rebinder(){
alert('rebinder');
$('.edit').click(texteditor);
$('#theText').attr( 'value', '' );
$('#theText').css('height', '');
$('#theText').css('width', '');
};
// End of document.ready function //
});
I just looked at the console and not only does the post happen twice but it posts the text from the second attempt to both post efforts which, unfortunately updates both elements with the .edit class. That’s bad…
You’re binding the submit event on the form multiple times. Move the binding out of the texteditor function or unbind the event before binding again.