Sign in to follow this  

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

This topic is 1772 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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>

 

 

Share this post


Link to post
Share on other sites

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)

Share this post


Link to post
Share on other sites

Why don't you try something like this?

 

 

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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
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. Edited by Nercury

Share this post


Link to post
Share on other sites
Sign in to follow this