0

i'm trying to parse a giphy url into a javascript parameter and it removes all my //.

This is my js:

var $save = $("<input type=\"button\" class=\"btn btn-sm btn-success\" value=\"Save\" onclick=\"SaveGif(\"" + gif.fixed_height.url +"\")\" />");

the url is:

https://media1.giphy.com/media/tJqyalvo9ahykfykAj/200.gif?cid=487fb615lw0p7lcstn5iqghh0mxvk4n889nope6ven1n897i&rid=200.gif

and this is what Chrome parses:

<input type="button" class="btn btn-sm btn-success" value="Save" onclick="SaveGif(" https:="" media1.giphy.com="" media="" tjqyalvo9ahykfykaj="" 200.gif?cid="487fb615lw0p7lcstn5iqghh0mxvk4n889nope6ven1n897i&amp;rid=200.gif&quot;)&quot;">

Also if i remove the quotes i get the correct url but without "":

<input type="button" class="btn btn-sm btn-success" value="Save" onclick="SaveGif(https://media1.giphy.com/media/tJqyalvo9ahykfykAj/200.gif?cid=487fb615lw0p7lcstn5iqghh0mxvk4n889nope6ven1n897i&amp;rid=200.gif)">

what i'm doing wrong?

thanks!

emboole
  • 501
  • 6
  • 23

3 Answers3

1

Use single quotes

var $save = $("<input type=\"button\" class=\"btn btn-sm btn-success\" value=\"Save\" onclick=\"SaveGif('" + gif.fixed_height.url + "')\" />");
Wilson Madrid
  • 437
  • 2
  • 7
0

wrap everything in ` backticks it allows you to use " " freely so it will be like this

var $save = $(`<input type="button" class="btn btn-sm btn-success" value="Save" onclick=SaveGif( + gif.fixed_height.url +/>`);
Ahmed Magdy
  • 1,054
  • 11
  • 16
0

If you open and close all that html string with single quotes you don't need any of the attribute double quotes escaped which makes it much easier to both read and write

Then rather than messing with inline onclick just add a jQuery event listener that calls your function with the appropriate variable passed in

var $save = $('<input type="button" class="btn btn-sm btn-success" value="Save" />');

$save.on('click', function(evt) {
  SaveGif(gif.fixed_height.url)
});

// demo code only below
const gif = {fixed_height: {url: 'https://media1.giphy.com/media/tJqyalvo9ahykfykAj/200.gif?cid=487fb615lw0p7lcstn5iqghh0mxvk4n889nope6ven1n897i&rid=200.gif'}};

$('body').append($save)

function SaveGif(url) {
  console.log(url)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
charlietfl
  • 170,828
  • 13
  • 121
  • 150