Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set inner HTML of a span element using jQuery

The following gives me the error Uncaught SyntaxError: Unexpected identifier:

$('span.xtro').html('');
$('span.xtro').html('<input type='button' class='newbutton send' value='Send request' onclick= 
                      "javascript:request('send','1','2');'>');

How can I correct this?

like image 316
Beraki Avatar asked Dec 06 '25 20:12

Beraki


2 Answers

You're not escaping the single quotes:

$('span.xtro').html('<input type="button" class="newbutton send" value="Send request"'
                  + ' onclick="request(\'send\',\'1\',\'2\');">');

You can also get rid of the first $('span.xtro').html('');, you shouldn't need it.

like image 168
BenOfTheNorth Avatar answered Dec 08 '25 09:12

BenOfTheNorth


It's not the best way of using jQuery... onclick attributes are not recommended. here's an alternative

//note wrapping with double quotes and using single ones inside 
var $el = $( "<input type='button' class='newbutton send' value='Send request'>" );
$el.on( 'click', function(){ request('send','1','2'); } ); 
$('span.xtro').html('').append( $el );

EDIT changed $el.bind to $el.on which is what is used nowadays

like image 22
gotofritz Avatar answered Dec 08 '25 08:12

gotofritz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!