javascript - append item to select box with jquery while escaping quotes - Stack Overflow

I'm adding options to a select box as follows:x.append("<option value="+option_to_ad

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

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

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

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

Share Improve this question edited Sep 3, 2021 at 8:56 Zoe - Save the data dump 28.3k22 gold badges128 silver badges160 bronze badges asked Mar 9, 2011 at 10:20 JorreJorre 17.6k33 gold badges103 silver badges147 bronze badges 3
  • 1 escape(option_to_add); should work I should think – Val Commented Mar 9, 2011 at 10:23
  • @Val: escape doesn’t do what you think it does in JavaScript. You must be thinking of PHP. – Mathias Bynens Commented Mar 9, 2011 at 10:29
  • @mathias it does encode the value, and u can decode it on server side – Val Commented Mar 9, 2011 at 10:30
Add a ment  | 

3 Answers 3

Reset to default 7

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./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>');

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745122168a4612477.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信