Dynamic input name with double quotes issue

怎甘沉沦 提交于 2019-12-25 14:17:08

问题


Scenario : When <div> text has double quote. JQuery method to append dynamic input and to alert the value of input is not working. I know this issue trigger when escaping quotes. Can someone review the code?

var divText = $("div").text();
$('form:not(:has([name="' + divText + '"]))').append($('<input>', {
  type: 'text',
  value: divText,
  name: divText
}));
alert($('[name="' + divText + '"]').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>"</div>
<form>

</form>

I've created some demo here


回答1:


Playing off the reg exp from the jQuery docs

var divText = $("div").text();
var name = divText.replace(/("|:|\.|\[|\]|,)/g, "\\$1");
$('form:not(:has([name="' + name + '"]))').append($('<input>', {
  type: 'text',
  value: divText,
  name: divText
}));
alert($('[name="' + divText + '"]').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>"</div>
<form>

</form>



回答2:


If you must use double quotes, you can remove them like so:

var divText = $("div").text().replace(/"/g, '');

Fiddle



来源:https://stackoverflow.com/questions/31576216/dynamic-input-name-with-double-quotes-issue

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