Xeptor
Xeptor

Reputation: 477

Append html with javascript string

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");

Upvotes: 1

Views: 101

Answers (4)

Siby Thomas
Siby Thomas

Reputation: 81

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>

Upvotes: 0

Kilian Stinson
Kilian Stinson

Reputation: 2394

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.

Upvotes: 1

Jay Ghosh
Jay Ghosh

Reputation: 682

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");

Upvotes: 1

suyesh
suyesh

Reputation: 659

$("<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

Upvotes: 0

Related Questions