user829982
user829982

Reputation: 121

Quotes breaking code in javascript onclick event using Jquery append

I am trying to pass two arguments in the on click javascript function. I need to enclose the the arguments in quotes. when i enclose it in single quotes it breaks the quote that starts from image and when i use double it breaks the quotes in front of javascript. how do i enclose it that it doesn't break my code?

$("#Div").append('<img id ="myImage" src ="/images/myimage.png"  onclick="javascript:myfunction('addnew',$("#field").val())"/> Error.')

Upvotes: 2

Views: 1566

Answers (4)

Esailija
Esailija

Reputation: 140230

You could do:

$("#Div").append( $( "<img>", {

    id: "myImage",

    src: "/images/myimage.png",

    click: function() {
        myfunction( 'addnew', $("#field").val() );
    }

}), " Error." );

Upvotes: 1

Barry Kaye
Barry Kaye

Reputation: 7761

Escape the single quotes around \'addnew\':

$("#Div").append('<img id ="myImage" src ="/images/myimage.png"  onclick="javascript:myfunction(\'addnew\',$("#field").val())"/> Error.')

Upvotes: 0

Anthony Atkinson
Anthony Atkinson

Reputation: 3248

You will have to escape the quotes with a backslash, as such:

$("#Div").append('<img id ="myImage" src ="/images/myimage.png"  onclick="javascript:myfunction(\'addnew\',$("#field").val())"/> Error.')

Upvotes: 2

Mathew Thompson
Mathew Thompson

Reputation: 56429

Try this, you need to escape the apostrophe with \:

$("#Div").append('<img id ="myImage" src ="/images/myimage.png" onclick="javascript:myfunction(\'addnew\',$("#field").val())"/> Error.')

Upvotes: 1

Related Questions