Escape/Special Characters from user input to HTML5 data-attributes using URL Encode/Decode

末鹿安然 提交于 2019-12-05 19:25:42

After much research I found the solution I was looking for. If you want to use escape/special characters in html5 data-attributes than a great solution would be to use encodeURI()/decodeURI(): http://www.w3schools.com/jsref/jsref_decodeuri.asp

Solution for this question:

Encoded url version of the value and set the value for select:

$.each(data, function(i, val) {
     var uri = val.typeName;
     var res = encodeURI(uri);
     var output = '<option id="' + this.qfInvoiceNum + '" class="type" data-name="' + res + '" >' + this.typeName +' | #' + this.qfInvoiceNum +'</option>';
     $('select#typeList').append(output);
    }); 

On select, grab the encoded uri, then decode uri

$('.selectChange2').change(function() {
    uriTypeGrab = $('select option.type:selected').data('name');
    typeGrab = decodeURI(uriTypeGrab);
});

typeGrab is now in the correct format with all of the escape/special characters and ready to pass to JSON.stringify() for the ajax call.

Not pretty sure to have really understood the whole question. Anyway, here is what I point out as perforce causing some issues.

When you create an <option> like this one:

'<option class="type" id="' + this.qfInvoiceNum + '" value="' + this.typeName + '">' + this.typeName +'</option>'

then this.typeName is used to populate both value attribute and node content.

In the latter case all is fine, as you reported, since the current typeName content has nothing special here, at the HTML point of view.

But in the value attribute, the content goes inside of quotes, and here it cannot be neutral as well.

Without more deeper analyzing and testing I can't be strictly affirmative, but a first, quite simply, attempt would be not to populate value attribute at all, using the HTML capability to transparently infer option value from its node content when no value has been given.

This way, the content should escape the constraints of the formulation in writing value. Let me know if it worked...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!