How to use inline JavaScript in HTML?

Saeed Neamati picture Saeed Neamati · Aug 13, 2011 · Viewed 53.5k times · Source

Support that I have this hidden field:

<input type='hidden' id='handler' name='handler' value='5534882394' />

And imagine that I fetch an HTML fragment from server via jQuery AJAX.

<div id='result'>
    <span></span>
</div>

However, instead of writing something like this:

$(function(){
   $('#result span').text($('#handler').val());
});

I'd like to use something like:

<div id='result'>
    <span>javascript:$('#handler').val();</span>
</div>

However, I don't get the intended result. Can I use this approach with JavaScript?

Update: Everybody please, I know about $(document).ready();. So, don't provide better ways. I just wanted to know if it's possible to have inline JavaScript, or not, and if yeah, how?

Answer

Guffa picture Guffa · Aug 13, 2011

No, you can't use that approach with Javascript. There is no such thing as inline Javascript.

What you see in a link like <a href="javascript:alert(1)"> is the javascript: pseudo-protocol, similar in use to the http: protocol. When you point the browser to such an URL, the browser runs the script.

If you want to run a script in the page, you need a script tag.