1

Im trying to append html with a javascript string, but having some troubles with the single quotes.

Appending the element works this far:

$("<a class='action-button' id='pl65197buy' value='buy now'>Bekijk aanbieding</a>").prependTo("div#centerplist");

But when I try to add an onclick function it wont work - do i need to escape the quotes somehow?

onclick="buy(this, 65197, null, 'pl65197qty",null, '/ajax/buy'

This is obviously wrong but its the closest i get without an error in the console:

$("<a class='action-button' id='pl65197buy' value='buy now' onclick='buy(this, 65197, null, 'pl65197qty',null, '/ajax/buy'>Bekijk aanbieding</a>").prependTo("div#centerplist");
1
  • Why the onclick and not an event handler in your javascript code? Commented Sep 21, 2016 at 7:51

4 Answers 4

1

You need to escape your quotes using the \ character. Try this

$("<a class='action-button' id='pl65197buy' value='buy now' onclick=\"buy(this, 65197, null, 'pl65197qty',null, '/ajax/buy')\">Bekijk aanbieding</a>").prependTo("div#centerplist");
Sign up to request clarification or add additional context in comments.

1 Comment

Really? Just to remove a "yes"?
1

I'd suggest a slightly different approach using an event handler in your javascript. This way its both easier to read and maintain.

$("<a class='action-button' data-id='165197' id='pl65197buy' value='buy now' >Bekijk aanbieding</a>").prependTo("div#centerplist");

$(document).on("click",".action-button",function() {
    // your buy() function 
    // $(this) contains your pressed button information
    buy($(this)[0], $(this).data('id'), null, 'p' + $(this).data('id') + 'qty', null, '/ajax/buy')
});

You're able to access the data-id attribute with $(this).data('id') for example.

EDIT: I've included your buy function, I wasn't if p+id+qty is generic or not, though I think you get how it works in general.

2 Comments

Hmm thats interesting. unsure how to write the function though
Edited my answer. Is it clearer now how I'd write the function inside the event handler?
0
$("<a class='action-button' id='pl65197buy' value='buy now' onclick=\"buy(this, 65197, null, 'pl65197qty',null, '/ajax/buy')\">Bekijk aanbieding</a>").prependTo("div#centerplist");

Try this

Comments

0

Try this.

<html>
<head> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
<body> 
<div id="centerplist">
</div>
<script>
$(document).ready(function()
{
$("#centerplist").prepend("<a class='action-button' id='pl65197buy' value='buy now' onclick='buy(this, 65197, null,\"pl65197qty\",null, \"/ajax/buy\")'>Bekijk aanbieding</a>");
});

function buy(p1,p2,p3,p4,p5,p6)
{
alert(p2);
}
</script>
</body> 
</html>

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.