[HTML5] I suck at it please help with short code

Started by
5 comments, last by Nercury 11 years, 1 month ago
What is so wrong with it -.-

<!DOCTYPE html>

<html>
<head>
</head>
<body>
    
<script>
    function meatball(x)
    {
        alert("I love " + x)
    }
    h = document.getElementById("hi");
</script>

<form>
    <input type="text" id="hi">
    <input type="button" id="ho" onclick="meatball(h)">
</form>

</body>
</html>

Advertisement

Is it possible that it is failing to find the text input element from inside the script tags because you're referring to an element that hasn't yet been created? (It's defined later on)

Why don't you try something like this?


function meatball() {
  var h = document.getElementById('hi').value;
  alert("I love " + h);
}

What is so wrong with it -.-

<!DOCTYPE html>

<html>
<head>
</head>
<body>
    
<script>
    function meatball(x)
    {
        alert("I love " + x)
    }
    h = document.getElementById("hi");
</script>

<form>
    <input type="text" id="hi">
    <input type="button" id="ho" onclick="meatball(h)">
</form>

</body>
</html>

Try moving all of the javascript code (including the 'script') tags into the <head> section of the HTML. When I run this on jsFiddle (jsFiddle.net) it runs fine for me.

You can't refer to an element which doesn't exist yet.

Consider having all non-trivial init code (and certainly all DOM code) in a function which executes on page load.

Thanks everyone!

Analogical code implemented using jquery would look like this:
<!DOCTYPE html>

<html>
<head>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
    
<script>
$(document).ready(function() { // this makes it execute only when DOM is loaded
    $("#ho").click(function() { // run this when element with id "ho" is clicked
        var $h = $("#hi"); // find element with id "hi"
        alert("I love " + $h.val());
    });
});
</script>

<form>
    <input type="text" id="hi">
    <input type="button" id="ho">
</form>

</body>
</html>
I am posting this as an example. Obviously, jQuery library takes some time to load, but it already solves many DOM manipulation tasks, and hides browser differences. The main advantage of jQuery is that your javascript is completely separate from HTML code.

This topic is closed to new replies.

Advertisement