HTML and Javascript integration

4

I'm doing some initial testing with javascript, and I'm not succeeding when trying to change a parameter from my HTML code. The idea is that by clicking the "Message" button, the text will be updated to "New Text!" Here is the HTML and javascript code:

<html>
<h1>Javascript</h1>
<h3 id="frase">Default text</h3>
<button id = "getMessage" class = "btn btn-primary"> Message </button>
</html>

$(document).ready(function() {
  $("#getMessage").on("click", function(){
    document.getElementById("frase").innerHTML = "New text!";
  });
});

How do I integrate what is displayed in HTML with my javascript code?

    
asked by anonymous 25.08.2016 / 18:24

2 answers

4

You need to add the jQuery bookstore and you also need to enter the TAG SCRIPT for JavaScript code.

Run the code below and see the script working.

<html>
<h1>Javascript</h1>
<h3 id="frase">Default text</h3>
<button id="getMessage" class="btn btn-primary"> Message </button>
</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$(document).ready(function(){$("#getMessage").on("click", function(){
    document.getElementById("frase").innerHTML = "New text!";
  });
});
</script>
    
25.08.2016 / 18:29
2

As mentioned, you are using code that is based on jQuery . You would need to include it first using a <script/> tag.

Being already included, you could rewrite your code as follows:

<script>
$(function() {
  $('#getMessage').on('click', function(){
    $('#frase').text('New Text!');
  });
});
</script>

The difference here is as follows:

  • $(function(){}) is a shortcut for document.ready
  • Since you are catching id of #getMessage , you can do the same #frase
  • $('#frase').text() exchange the text that is inside. If you are going to put HTML yourself (e.g. <span>Algo</span> ), you would use $('#frase').html()
25.08.2016 / 18:52