Place Javascript function inside onclick

Asked

Viewed 54,475 times

4

So it’s kind of a silly question, but I really need... has how I put a Javascript function inside a buttom in this example below it calls the function loadDoc(). more I would like to put the function directly inside the onclick.

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
  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();
}
</script>

</body>
</html>

Source: http://www.w3schools.com/code/tryit.asp?filename=FAK6YYP9UBMF

  • Putting all this inside a single button would almost obstruct the HTML unnecessarily, it would be better to put the loadDoc inside a file with the extension. js

  • I know that I am trying to implement a taghelper in c# will be all via code Behind, and at first I will try this way

  • You better edit the question, because ae changes the whole meaning. If not people answer one thing and you want another. Please give details.

  • the question this correct I want to know that there

  • It wasn’t clear to you ?

  • All right, I’ll formulate an answer.

  • a since from the moment I look at an example putting the whole function within the onclick the rest I can manage to do, but it will not stay that way no, I just want to see an example so I can make the taghelper. Thank you :)

  • Independent of the taghelper after the generated html you can do all interaction in the . js file by DOM control. Doing everything inline can be a problem.

Show 3 more comments

2 answers

8


Using anonymous function

<input type="button" value="anonymous function" onclick="(function(){
console.log('ok');
console.log('ok2');
})()">

In this snippet I just wanted to show that it is possible to apply line breaks, making the code more readable.

Implementing for your specific case:

<input type="button" value="anonymous function" onclick="(function(){
    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();
    })()">

In case of sending parameters to the function

In your case there is no passing of parameters. If you want to pass parameters to the function, see this example

<input type="button" value="anonymous function" onclick="(function(v){
console.log(v);
console.log('ok2');
})('ok')">

Remarks

Obviously, any web developer who understands the basics is aware of good practices and semantics, however, situations can occur where there is no way to follow a correct semantics or even such questions are out of context. It is not necessary to judge whether what you intend to do is correct or not because the business model, reasons, or circumstances are not explicit.

  • perfect guy exactly what was looking for vlw

4

There’s no reason to put a whole script inside a single button

  • It is possible? The answer is yes
  • Is recommended? The answer is nay

I’ll explain later why it’s not recommended.

Inline example

Even if it is not recommended I will give an example, to solve you need to exchange the quotes for "single quotes" (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>

Note that the page http://www.w3schools.com/code/tryit.asp?filename=FAK6YYP9UBMF is not working due to a browser security lock, it is w3schools.com’s fault and not even from the script.

What is preferable

Best is to move every script into a file .js, model independent, circumstances; anyway it is possible to avoid all this using GIFT and no one is judging, this is an orientation of how to avoid problems and show that a lot is possible.

Use everything in files .js will bring you advantages such as:

  • Resource cache
  • Reuse of code
  • Decrease the HTML
  • Avoid obstructing the HTML
  • Facilitates organizing

An example, create a file called app.js and put 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>

Look, it gets a lot less polluted

  • so I tried tbm this way more not sure of a look http://www.w3schools.com/code/tryit.asp?filename=FAK7UG7C6S75

  • @Warlesonreis I edited the answer, try this https://jsfiddle.net/vb4psohm/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.