You do not have to put a whole script inside a single button
-
Is it possible? The answer is yes
-
Is it recommended? The answer is no
I will explain later why it is not recommended.
Inline example
While not being recommended, I'll give you an example, to resolve you need to change the quotes to "single quotation marks" (apostrophes):
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById('demo').innerHTML = this.responseText; } }; xhttp.open('GET', 'ajax_info.txt', true); xhttp.send();">Change Content</button>
</div>
</body>
</html>
Please note that the link page is not working due to a browser security lock, is w3schools.com's fault and not the script itself.
What is preferable
It is best to move every script into a .js
file, regardless of model, circumstances; anyway you can avoid all this using DOM and no one is judging, this is a guidance on how to avoid problems and show that much is possible.
Using everything in .js
files will bring you advantages like:
- Resource Cache
- Code reuse
- Decreased HTML
- Avoid obstructing HTML
- Easy to organize
For example, create a file named app.js
and place this content:
function ready(callback)
{
if (/^(interactive|complete)$/i.test(doc.readyState)) {
callback();
} else {
doc.addEventListener('DOMContentLoaded', callback);
}
}
function loadDoc(url, callback, error)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.responseText);
} else if (error) {
error(this.status);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
//Equivale ao $.ready do jQuery
ready(function() {
var botao1 = document.getElementById("botao1");
var botao2 = document.getElementById("botao2");
botao1.onclick = function() {
loadDoc("ajax_info1.txt", function(resposta) {
document.getElementById("demo").innerHTML = resposta;
});
};
botao2.onclick = function() {
loadDoc("ajax_info2.txt", function(resposta) {
document.getElementById("demo").innerHTML = resposta;
});
};
});
And the html should look like this:
<!DOCTYPE html>
<html>
<head>
<title>Exemplo</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id="demo"></div>
<button id="botao1">Testar 1</button>
<button id="botao2">Testar 2</button>
</body>
</html>
Looks much less polluted