I am new to jQuery, so I am sure that I am doing something wrong, but I can not understand why this event is not shooting. I have a textarea element that needs to be deleted before sending due to the application receiving the data. I am trying to do this clear in a text box when it loses focus, hence the blur method. Unfortunately, it does not work in my form. The strange part is the same code as in jsFiddle, but only with the initial loss of focus. All subsequent changes to textarea and loss of focus do not trigger the event. I also read in another answer that the delegate() or .on() methods might be needed, but I'm not 100% sure how to do this correctly. ( jQuery blur () not working? ) The code below, any advice would be helpful.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#comments").blur(function() { var txt = $("#comments").html(); txt = txt.replace(/\n/g, ' '); txt = txt.replace(/\s{3,}/g, ' '); $("#comments").html($.trim(txt)); }); </script>
HTML:
<textarea name="comments" id="comments" style="width: 100%; height:200px"></textarea>
And here is the jsFiddle link: http://jsfiddle.net/75JF6/17/
EDIT: Thanks for all the quick answers. I looked through all the answers and accepted your advice. I'm 95% of what I have, but the problem still persists. Switching to the .val() method instead of .html() is the best way to do this, but according to the jQuery API, when calling this method on textarea , where the carriage return is performed, the following problem occurs. The problem is that I need to make sure they are deleted to validate the field.
Note. Currently, using .val() on textarea elements, they .val() carriage return characters from the value specified in the browser. When this value is sent to the server via XHR, however, the carriage return is saved (or added by browsers that do not include them in the original value). A workaround for this problem can be achieved with valHook as follows:
$.valHooks.textarea = { get: function( elem ) { return elem.value.replace( /\r?\n/g, "\r\n" ); } };
As I mentioned earlier, I'm new to jQuery and could not find much information on how to use valHooks between google and stack overflows correctly. If anyone can shed light on this in relation to my original question, we will be very grateful.