1

I have an issue with onclick function.

Here's my code :

$('ul.listing').append('<button onclick="openInApp("test")"  class="btn btn-primary">Edit <i class="fa fa-external-link" aria-hidden="true"></i></button>');

When I click the button, I have the "Unexpected end of input" error message. I try to pass variable too like this :

$('ul.listing').append('<button onclick="openInApp('+ edit_url +')"  class="btn btn-primary">Edit <i class="fa fa-external-link" aria-hidden="true"></i></button>');

And I get the following message : Uncaught SyntaxError: missing ) after argument list

Both errors begins at the "("

I have another function (always in the append) :

 $('ul.listing').append('<a href="event-details.html" onclick="saveEventID(' + data[i].ID + ');">')

And it works perfectlly

I don't understand

5
  • 2
    Since you used onclick="openInApp("test")", only "openInApp(" is passed to the onclick listener Commented May 14, 2018 at 17:52
  • 3
    Your problem is conflicting quotes, try to avoid using attribute event handlers, these are just one of several issues that come up when using them. Commented May 14, 2018 at 17:54
  • I know that the probleme is the quotes but how to solve it ? I try to inverse double quote and quote, to remove it, etc but still the same problem. Also why the other function worked ? Commented May 14, 2018 at 17:59
  • 2
    You can escape the quotes with a backspace, or use a string template, or you can bind the event handler to the element as a non-inline binding. There are various ways to approach this issue. Commented May 14, 2018 at 18:02
  • Just don't use inline event attributes at all. Bind the function using jQuery on. Commented May 14, 2018 at 18:07

1 Answer 1

5

To nest the string in the onclick, you can do it like below where the single quote is escaped using a backslash to prevent it from terminating the string.

$('ul.listing').append('<button onclick="openInApp(\'test\')"  class="btn btn-primary">Edit <i class="fa fa-external-link" aria-hidden="true"></i></button>');

An alternative way to handle this can be done by passing the string through a separate data attribute:

$('ul.listing').append('<button onclick="openInApp(this)" data-string="yourstringhere" class="btn btn-primary">Edit <i class="fa fa-external-link" aria-hidden="true"></i></button>');

and then accessing it in the onclick function like this:

function openInApp(element) {
    var mystring = $(element).data("string");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.