Search code examples
jqueryhtml-encode

how to check the input value is html encoded


is there any way to check if a text box value is already html encoded or not.

For page validation i am using the following code on focus out of a textbox.

    $(document).ready(function() {
        $('#txtLink').focusout(function(){
            $('#txtLink').val(htmlEncode($('#txtLink').text()));
        });
    });
    function htmlEncode(value){
        if (value) {
            return jQuery('<div />').text(value).html();
        } 
        else {
            return '';
        }
    }

    function htmlDecode(value) {
        if (value) {
            return $('<div />').html(value).text();
        } 
        else {
            return '';
        }
    }

for every focus out of the text box or alt+tab to other window etc... text is encoding multiple times. need some suggestions.

Thanks in advance


Solution

  • I think you're confusing client side and server side efforts. When you set a val of an element that happens to contain HTML entities on the server side, you have to encode it because it needs to know that all that text is a part of the value and NOT new markup. When client side, you can just set the value, e.g. $('#txtLink').val('<div>Hello <span>World</span></div>') No encoding/decoding necessary for setting or retrieving (or posting)