Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use inline JavaScript in HTML?

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?

like image 805
Saeed Neamati Avatar asked Aug 13 '11 13:08

Saeed Neamati


People also ask

Can we use inline JavaScript in HTML?

Inline JavaScript can be achieved by using Script tag inside the body of the HTML, and instead of specifying the source(src=”…”) of the JavaScript file in the Script tag, we have to write all the JavaScript code inside the Script tag.

How use internal JavaScript in HTML?

Adding JavaScript into an HTML Document You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.

How do I use external JavaScript in HTML?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

What is inline JavaScript?

In JavaScript, inline function is a special type of anonymous function which is assigned to a variable, or in other words, an anonymous function with a name.


1 Answers

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.

like image 171
Guffa Avatar answered Oct 05 '22 02:10

Guffa