1

The following simple html page is not responding to as it should when click on either "click" or "hide all paragraphs" button.I have included jquery lib "jquery-1.9.1.min.js" and I can see its all content in Firefox's 'view source page' by click it.This file's url in my browser is:mylocalhost:8080/ajaxAppJquery/tryAjax.jsp.Using Netbeans IDE.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <title>Simple Ajax Example</title>
        <script src="jquery-1.9.1.min.js"></script>
        <script>
            $("#button").click(function(){
                alert("working");
                var url="http://localhost:8080/ajaxAppJquery/sayHello.jsp";

                $("#result").load(url);
            });

            $("#hide").click(function(){
                $("p").hide();
            })
        </script>
    </head>
    <body>
        <input id="button" value="click" type="button"/>

        <input id="hide" value="hide all paragraphs" type="button"/>
        <p>paragraph 1</p>
        <p>paragraph 2</p>
        <p>paragraph 3</p>
        <p>paragraph 4</p>
        <p>paragraph 5</p>
        <p>paragraph 6</p>

        <div id="result"></div>
    </body>
</html>

When i click on #button it does not alert the message.Actually I am experimenting with jquery-ajax but it is not working with #hide button also.

3 Answers 3

2

You are accessing the html elements in script before they are available, You should put the script in document.ready or put the script just before the closing body tag

$(document).ready(function(){
    $("#button").click(function(){
         alert("working");
         var url="http://localhost:8080/ajaxAppJquery/sayHello.jsp";
         $("#result").load(url);
     });

     $("#hide").click(function(){
         $("p").hide();
     })    
});
Sign up to request clarification or add additional context in comments.

1 Comment

No worries, Some time we miss simple things.
1

Wrap your jquery code inside $(document.ready(function() {}) or $(function() {}); to let it see the whole DOM:

$(document).ready(function(){
    $("#button").click(function(){
        alert("working");
        var url="http://localhost:8080/ajaxAppJquery/sayHello.jsp";

        $("#result").load(url);
     });

     $("#hide").click(function(){
         $("p").hide();
     })
});

Comments

1

try to bind event after DOM ready

$(document).ready(function() {
  $("#button").click(function(){
    alert("working");
    var url="http://localhost:8080/ajaxAppJquery/sayHello.jsp";
    $("#result").load(url);
  });

  $("#hide").click(function(){
    $("p").hide();
  })
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.