문제

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");
도움이 되었습니까?

해결책

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');
    }
});

다른 팁

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/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top