Reputation: 3043
Hi How can I define a function on button click in HTML, I tried something like that:
<input type="button" value="sth" onclick="
<script type="text/javascript">
function hello()(
window.print();
var z =document.GetElementById('ogog');
z.inneHTML="hello";
<script>
">
I have to define my function here because I have code which generate me a site in which's header i can not define javascript function and I want one function on button click. this is only an example. This is the way it should look like?
Upvotes: 6
Views: 31556
Reputation: 2624
You can also put code directly, as for example a jQuery call, as for example onclick="$('#confirmation_modal').modal();"
to open a modal or onclick="$('#confirmation_modal').modal('toggle');"
to close it.
Or also you can define a function and call it after.
Upvotes: 1
Reputation: 1
yyesThis code will be executed when the button is clicked. In general, the script tag is used to define scripts that can be referenced elsewhere in the HTML document, while strings containing JavaScript code are used in the body of the document to actually execute that code.
Upvotes: 0
Reputation: 29668
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()"/>
Upvotes: 4
Reputation: 10955
Assuming you realy want to define a new funciton on your onclick event you can try this:
<input type="button" value="something" onclick="window.hello=function(){window.print();var z =document.GetElementById('ogog');z.innerHTML='hello';}">
Upvotes: 5
Reputation: 963
You don't have to open the script tags, you just need to write directly the code you need.
You'd better include it inside a function defined in the head section, though:
<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>
Upvotes: 3
Reputation: 55529
You will have to define the script tag in the same file first, also '{' for function definitions -
<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()"/>
Check this link for more details.
Upvotes: 2
Reputation: 373472
You can attach a script to a button by putting a string representation of that script in the onclick handler:
<input type="button" onclick="window.alert('Hi!')">
This code will be executed when the button is clicked. In general, the script tag is used to define scripts that can be referenced elsewhere in the HTML document, while strings containing JavaScript code are used in the body of the document to actually execute that code.
Upvotes: 6