Edeph
Edeph

Reputation: 772

Button tag onclick not working

I try to inject a button in a page and i want to make it clickable but it seems it's not working at all.

$(".something").append('<button style="background-image: \
-webkit-gradient(linear, left bottom, left top, color-stop(0.3, rgb(255,170,0)),\
color-stop(0.85, rgb(222,133,0)) ); height: 28px; padding-top: 5px; \
padding-bottom: 5px; padding-left: 10px; padding-right: 10px; \
border-top-left-radius: 4px; border-top-right-radius: 4px; \
border-bottom-left-radius: 4px; border-bottom-right-radius: 4px;" \
type="button" onclick="alert("lelele");"><span style="color: #fff;">\
Button</span></button>');

I searched the web and i went trying the simplest solution: the alert function and even that is not working.

Upvotes: 1

Views: 3481

Answers (3)

xec
xec

Reputation: 18024

Your quotes are mismatched, try escaping the inner ones.

onclick="alert(\'lelele\');"

That said, onclick is the old way of doing things, you will get cleaner code avoiding inline JavaScript (like bipen suggests).

$(".something")
    .append('<button class="myClass">Button</button>') // no CSS or inline JavaScript
    .on("click", "button", function() { // delegation syntax
        alert("lalala");
    });

Read more about event delegation syntax here

Also move your styles to a css file! :)

Upvotes: 1

bipen
bipen

Reputation: 36531

the problem is with escaping....

onclick="alert(\'lelele\');"

but i prefer using on delegated event

 $(function(){
  $('.something').on('click','button',function(){
     alert('lelele');
  })
 });

this won't require the inline onclick javascript event which is hard to read and debug...

remove onclick="alert("lelele");" from button

Upvotes: 3

Nicolas Dusart
Nicolas Dusart

Reputation: 2007

Use simple quotes in the onclick argument. You have to escape them because you use them as delimiter in your append function.

onclick="alert(\'lelele\');"

Upvotes: 0

Related Questions