Question

I have a form with some <textarea> elemets that has need to be validated so that it\they can not hold pipe lines |. following is the code, please let me know if it is missing anything!

$(".no_pipes").blur(function() {
    var str = $(this).val();
    alert(str); // ---> it alerts nothing!
    if (str.indexOf("|") >= 0) {
        alert("The informatin you provided contains illegal characters(\"|\")");
        $(this).css('border', '1px solid pink');
        var that = $(this);
        setTimeout(function() {
            that.focus()
        }, 0);
    } else {
        $(this).css('border', '1px solid #ccc');
    }
});

I use an ADD button to add more <textarea> fields to the form!

var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<textarea class="no_pipes" name="field[value][]" required ></textarea>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
Was it helpful?

Solution

You have to use delegation, use focusout event instead of blur, blur event doesn't bubbles and delegation need propagation to work:

$(document).on('focusout',".no_pipes",function() {
    var str = $(this).val(); // you could use this.value instead
    alert(str); // ---> it alerts nothing!
    if (str.indexOf("|") >= 0) {
        alert("The informatin you provided contains illegal characters(\"|\")");
        $(this).css('border', '1px solid pink');
        var that = $(this);
        setTimeout(function() {
            that.focus()
        }, 0);
    } else {
        $(this).css('border', '1px solid #ccc');
    }
});

OTHER TIPS

The blur event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the blur event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping blur to the focusout event in its event delegation methods, .live() and .delegate().

See more here:

http://api.jquery.com/blur/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top