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
-
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
3 Answers
Reset to default 7I 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条)