문제

I have this function to add text to a textarea when it gains focus ONLY when it's empty but for some reason, it will add the text when there is already content and sometimes it won't add anything when it's empty.

I am using TamperMonkey to add this script to a forum board I frequent.

I am first checking the value of the textarea to see if it's blank. If it is, it should continue to the next function. When the textarea gains focus, it adds text to the textarea.

Script:

$(document).ready( function() {
    var text = '<div style="color:#72008c;font-size:13px;">\n\n</div>';
    var el = $('textarea#Form_Body');

    if( el.val() == "" ) {
        el.focus( function() {
            el.val(text);
        });
    }
});
도움이 되었습니까?

해결책

Ok I feel stupid... I've got the logic wrong. I should have had the if statement inside the focus function.

$(document).ready( function() {
    var text = '<div style="color:#72008c;font-size:13px;">\n\n</div>';
    var el = $('textarea#Form_Body');

    el.focus( function() {
        if( el.val() == '' ) {
            el.val(text);
        }
    });
});

This works perfectly now.

다른 팁

Add your IF Statement inside the focus loop...

$(document).ready( function() {
    var text = '<div style="color:#72008c;font-size:13px;">\n\n</div>';
    var el = $('textarea#Form_Body');

        el.focus( function() {
          if( el.val() == "" ) {
            el.val(text);
        });
    }
});

Hope it helps

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