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