简体   繁体   中英

jQuery blur event not firing

I'm new to jQuery, so I bet I'm doing something wrong, but I cannot figure out why this event is not firing. I have a textarea element that needs to have any breaking spaces removed prior to submission due to the application that is accepting the data. I am attempting to do this clean up in the textarea when it loses focus, hence the blur method. Unfortunately it does not appear to fire within my form. The weird part is the same code works in jsFiddle, but only upon the initial loss of focus. All subsequent changes to the textarea and loss of focus does not fire the event. I also read in another answer that the delegate() or .on() methods might need to be used, but I'm not 100% sure how to do this properly.( jQuery blur() not working? ) Code is 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));
});

//$("#comments").trigger("blur"); added this to help fix the issue, but it didn't make a difference
});
</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 fast responses. I have looked into everyone's answers and taken your advice. I'm 95% of the way there, however, there is still an issue that persists. Switching to the .val() method instead of .html() is a better way of doing this, but according to the jQuery API the following issue exists when calling this method on textarea s where carriage returns are parsed out. The issue is that I need to make sure they are removed to validate the field.

Note: At present, using .val() on textarea elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a 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 regarding how to properly use valHooks between google & stack overflow. If anyone can shed some light on this in relation to my original question it would be greatly appreciated.

You code is working perfectly fine.

Also attach the click event on the submit button, as there is no blur event happening when you click the button. you have to explicitly make the textarea lose focus.

$(document).ready(function () {
    $("#comments").on('blur', trimText);
    $("input[type='submit']").on('click', function (e) {
        e.preventDefault();
        trimText();
        $("input[type='submit']").submit();
    });

    function trimText() {
        var txt = $("#comments").html();
        txt = txt.replace(/\n/g, ' ');
        txt = txt.replace(/\s{3,}/g, ' ');
        $("#comments").html($.trim(txt));
    }
});

Check Fiddle

It's not required to add delegate() or on() to the element, it's only required if they are dynamically added, deleted, etc. but it won't hurt to try.

For your example, replace:
$("#comments").blur(function() {
With:
$(document).on("blur","#comments",function() {

Also, can you check thru developer tools of chrome/firefox/safari/etc if it's giving errors in the console?

You were close. The on() event in jQuery is probably one of the most resource tools you have available to you, but there are few different ways to mark it up.

$("#comments").on({
    'blur' : function() {
        // your magic here
    }
});
$("#comments").trigger("blur");

I forked your jsFiddle to get what you had working. http://jsfiddle.net/75JF6/33/ You were close and were on the right track. Think of the on() event as adding callback functionality to any event out there. I hope that helps!

Right way: http://jsfiddle.net/75JF6/35/

$(document).ready(function() {
    $("textarea#comments").on('blur',function() {
        var txt = $(this).val();
        txt.replace(/\n/g, ' ');
        txt = txt.replace(/\s{3,}/g, ' ');
        $(this).val($.trim(txt));
    });
});

val() should be used for form input elements, textarea is no different.

It works with val() instead of html()

i think it's because html value doesnt update the actual content of DOM tree

$(document).ready(function() {
    $("#comments").blur(function() {

        var txt = $("#comments").val();

        txt = txt.replace(/\n/g, ' ');
        txt = txt.replace(/\s{3,}/g, ' ');

        $("#comments").val($.trim(txt));
});
});

Use On, delegate or Live only when you are appending the target element after the DOM ready.

you can use keyup to do the same, except that it fires at every keystroke. The following code will fire when user is waiting for 300 ms after typing. it will be faster than the blur event.

var ClearInterValHandel;
var interval = 300 //in milisecond.

$("#comments").keyup(function(){
ClearTimeOut(ClearInterValHandel);

ClearInterValHandel = SetTimeout(trimText, interval);    
});

function trimText() {
        var txt = $("#comments").html();
        txt = txt.replace(/\n/g, ' ');
        txt = txt.replace(/\s{3,}/g, ' ');
        $("#comments").html($.trim(txt));
    }

A combination of answers from @Sushanth -- and @Eez along with some additional research brought me to the correct answer to this question. Thank you for your input, which put me on the right path. I'm going to set this answer as community wiki.

Both changing the retrieval method from .html() to .val() as well as using the .on() function solved the issue I was experiencing. Since the form field "#comments" was a textarea it experienced a known issue within the jQuery API: http://api.jquery.com/val/

Below is the code that actually resolved the issue:

$(document).ready(function () {
    $.valHooks.textarea = {
        get: function (elem) {
            return elem.value.replace(/\r?\n/g, "<br>\n");
        }
    };


$("#comments").on('blur', trimText);
$("input[type='submit']").on('click', function (e) {
    e.preventDefault();
    trimText();
    $("form:first").submit();
});

function trimText() {
    var txt = $("#comments").val();
    txt = txt.replace(/<br>\n/g, ' ');
    txt = txt.replace(/\s{3,}/g, ' ');
    //alert(txt);
    $("#comments").val($.trim(txt));
  }


});

I forked @Sushanth-- 's jsFiddle again to include all of this information if anyone is interested: http://jsfiddle.net/B3y4T/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM