0

i have the following markup/code

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>

   <script src="directory for jquery script">
    $(document).ready(function () {
        $("button").on('click', 'test', function() {

            var webserUrl = "http://wsf.cdyne.com/WeatherWS/Weather.asmx";
            var soapRequest = '<ns1:GetWeatherInformation     xmlns:ns1=\'http://ws.cdyne.com/WeatherWS/\' />';
            $.ajax({
                type: "POST",
                url: webserUrl,
                contentType: "text/xml",
                dataType: "xml",
                data: soapRequest,
                success: SuccessOccur,
                error: ErrorOccur
            });
        });
    });
    function SuccessOccur(data, status, req) {
        if (status == "success")
            alert(req.responseText);
    }
    function ErrorOccur(data, status, req) {
        alert(req.responseText + " " + status);
    }
</script>

</head>
<body>



<button id="test">Test</button>

on click of the test button i would like the soap request to be sent but for some reason when i click the button nothing happens, i can confirm it is picing up jquery.js (2.1.1).

I am sure it is a silly mistake but I am not seeing it, the code i have (this is a reworked version) works fine but this code does not.

Any help in picking out the issue is greatly received.

1
  • I have retracted my close vote as there are multiple issues (not just the simple typo). Hopefully all now covered below :) Commented Sep 22, 2014 at 15:11

4 Answers 4

10

Typo #test. An id selector needs the # prefix.

$("button").on('click', '#test', function() {

and yes, it was a silly mistake. I call this situation code-blindness.. looked at it so long you can't see the problems any more :)

Important update

You are currently misusing a delegated event handler. I assumed that was with good reason (like dynamically replacing the page content), otherwise you can simplify the handler, but that is too trivial to bother with.

The current handler would not survive dynamic content as it binds to buttons directly, then applies the filter. If the buttons were added/replaced dynamically they would not bind to the new ones.

A proper delegated event handler would be

$(document).on('click', 'button#test', function() {

or, as it is an id look-up, simply

$(document).on('click', '#test', function() {

Delegated event handlers work by listening for events (in this case click) bubbling up to a non-changing ancestor (document if nothing else is convenient. Never use 'body' as it has click bugs due to styling issues), then it applies a jQuery selector to the bubbling elements, then it applies the function to any matching elements that caused the event. This will allow it to work on elements that do not exist at the time the code was run, but will exists when the event happen (very handy).

Notes:

As Pete TNT also points out, the script block does not appear to be valid. Please check that too :)

Sign up to request clarification or add additional context in comments.

6 Comments

I am curious to how this actually works - it doesn't when I try to fiddle it. As I understand from the jquery API, doesn't this actually try to bind the handler to every button element, and pass #test as data to the event?
@Ivo Coumans: #test is not data. It is a filter for the delegated event handler applied at click time.
I don't mean to contradict you or anything, but it's not in the jquery documentation and it's not working for me. Could you provide a working jsfiddle?
@Ivo Coumans: Have you also fixed the other problems (script block etc)?
It was the quotes around document. Thanks for helping me understand though, I had no idea click could be used like this.
|
1

In addition of not having the # prefix, you also seem to be writing the code inside of the script tag that already points to an external file, which omits everything inside it.

<script src="js/jquery.js"></script>
<script type="text/javascript">

     $(document).ready(function () {
            $(document).on('click', '#test', function() {
                /* and so on */
            });
      });
</script>

(Unless you are using something like Resigs degrading script-tags)

2 Comments

+1: Good point about the script block... The more I look at the code the more problems I am finding. Note: The delegated handler $("button").on('click', '#test' will not work for dynamic content as it needs to bind to a non-changing ancestor.
Yup, that's true too.
0

You can use the shorthand for onclick as well, which would make your code a little simpler:

$("button").click(function() {
    // body here
});

Assuming you want the click function to bind to all button elements on your page, but you probably just want it to bind to the #test button. In that case, you'll have to use $("#test") instead:

$("#test").click(function() {
    // body here
});

1 Comment

I assumed from the code that the content may be dynamic, so left the delegated event handler.
0

Another alternative would be to use the shorthand:

$('#test').click(function() {
    // Oh yeah
});

3 Comments

I assumed from the code that the content may be dynamic, so left the delegated event handler.
Interesting...Can you explain a bit more? I'm curious what you mean by "dynamic content" that would require the delegated event handler.
If the page content is replaced dynamically a normal event handler would be disconnected and even if an identical id reappeared the click binding would be gone. delegated event handlers listen for bubbled events at a non-changing ancestor (default document if nothing else available), then apply the jQuery selector.

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.