-1

I want to add elements to the HTML body, but I have a problem. the onclick function doesn't work because I blew the wrong one in the function. the following is the append code in my html

var html= "<button class='btn fab-success' type='button' onclick='openTabGeneral('tab_map', 'Web GIS', 'client/map/index.html', 'Get', 'yes')'>Click</button>";
$("body").append(html);

the result of that html code is

onclick="openTabGeneral(" 'tab_map'',''webgis'',''client/map/client="" map="" index.html'',''get'',''yes'')'=""

i want the result like this

onclick="openTabGeneral('tab_map', 'webgis', 'client/map/index.html', 'get', 'yes')"

please tell me how to change the code like this ^

R ford
  • 9
  • 5
  • 1
    it is much easier to create the node with `document.createElement()` instead of appending an html string... at least, I think, much more control over the element – Calvin Nunes Feb 05 '20 at 16:19
  • 1
    you need to escape single quotes : \'tab_map\', for example – Pierre Feb 05 '20 at 16:20
  • 1
    Does this answer your question? [Escape quotes in JavaScript](https://stackoverflow.com/questions/2004168/escape-quotes-in-javascript) – Alon Eitan Feb 05 '20 at 16:21
  • 2
    In addition to @CalvinNunes point, it's much better practice to use unobtrusive event handlers instead of outdated `onclick` attributes. Then you avoid this issue entirely. – Rory McCrossan Feb 05 '20 at 16:28

1 Answers1

1

The short term fix is to escape the quotes within the attribute you create in the HTML string:

var html = '<button class="btn fab-success" type="button" onclick="openTabGeneral(\'tab_map\', \'Web GIS\', \'client/map/index.html\', \'Get\', \'yes\')">Click</button>';
$("body").append(html);

function openTabGeneral() {
  console.log(arguments);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

However, the much better approach is to build the Element manually, and to use an unobtrusive event handler on it which avoids the issue entirely. To do that you can use a delegated event handler and data attributes, like this:

$(document).on('click', 'button', function() {
  console.log($(this).data()); // all arguments
  console.log($(this).data('arg1')); // specific argument
});

$('<button />', {
  'class': 'btn fab-success',
  'type': 'button', 
  'text': 'Click',
  'data-arg1': 'tab_map',
  'data-arg2': 'Web GIS',
  'data-arg3': 'client/map/index.html',
  'data-arg4': 'Get',
  'data-arg5': 'yes' // this should probably be a boolean, not a string
}).appendTo('body');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339