Define function in javascript onbuttonclick

Hi How to define a function when a button is clicked in HTML, I tried something like this:

<input type="button" value="sth" onclick=" <script type="text/javascript"> function hello()( window.print(); var z =document.GetElementById('ogog'); z.inneHTML="hello"; <script> "> 

I need to define my function here because I have a code that generates a website for me in which header I cannot define a javascript function, and I want one function to be pressed on a button. this is just an example. So should it look like?

+5
source share
7 answers

Assuming you really want to define a new function in your onclick event, you can try the following:

 <input type="button" value="something" onclick="window.hello=function(){window.print();var z =document.GetElementById('ogog');z.innerHTML='hello';}"> 
+4
source

You can attach a script to a button by placing a string representation of this script in the onclick handler:

 <input type="button" onclick="window.alert('Hi!')"> 

This code will be executed when the button is pressed. In general, the script tag is used to identify scripts that can be referenced elsewhere in the HTML document, while lines containing JavaScript code are used in the text of the document to actually execute that code.

+6
source

You do not need to open script tags, you just need to write the code that you need.
You better include it in the function defined in the section of the chapter:

 <head> <script type="text/javascript"> function hello () { ... } </script> </head> <body> <input type="button" onclick="hello()" /> </body> 

or, even better, load it from an external .js file:

 <script type="text/javascript" src="scripts.js"></script> 
+3
source

You might want to try:

 <script type="text/javascript"> function hello() { window.print(); var z =document.GetElementById('ogog'); z.inneHTML="hello"; } </script> <input type="button" value="sth" onclick="hello()"/> 
+3
source

First you need to define a script tag in the same file, and also '{' to define functions -

 <script type="text/javascript"> function hello() { window.print(); var z =document.GetElementById('ogog'); z.inneHTML="hello"; } </script> 

Then call the function with its name -

 <input type="button" value="sth" onclick="hello()"/> 

See the link for more details.

+2
source

yyes This code will be executed when the button is clicked. In general, the script tag is used to identify scripts that can be referenced elsewhere in the HTML document, while lines containing JavaScript code are used in the text of the document to actually execute that code.

0
source

You can also put code directly, such as a jQuery call, for example, onclick="$('#confirmation_modal').modal();" to open the modal window, or onclick="$('#confirmation_modal').modal('toggle');" to close it.

Or you can also define a function and call it after.

0
source

Source: https://habr.com/ru/post/1337748/


All Articles