开发者

append item to select box with jquery while escaping quotes

I'm adding options to a select box as follows:

x.append("<option value="+option_to_add+">"+option_to_add+"</option>");

where "option_to_add" can be any value a user has entered. Of course, a problem arises when adding options that have single or double quotes in them.

Is there a way to escape these values correctly before appending them to a select list

e.g. this will be a problem

开发者_Python百科user types: he"llo my code will try to append this as : <option value="he"llo"/> which crashes the html/js


I found a native jQuery way to handle this correctly:

.append($("<option></option>").attr("value",option_to_add).text(option_to_add));


You could you the Javascript replace function to escape or remove the quotes... http://www.w3schools.com/jsref/jsref_replace.asp


You’ll need to escape the " characters, like this: \"

This can be automated as follows:

'foo"bar"baz'.replace(/"/g, '\\"'); // 'foo\"bar\"baz'

You’ll only need to do this for the value attribute of the <option> element, so the full code snippet would be:

x.append('<option value="' + option_to_add.replace(/"/g, '\\"') + '">' + option_to_add + '</option>');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜