1

I am trying to assign a click event to span elements with class 'open' and 'appoint'. But I cannot get it to work. Code is as shown below.

HTML:

            <td><span id = "28" class='open'>28</span></td>
            <td><span id = "29" class='open'>29</span></td>
            <td><span id = "30" class='closed'>30</span></td>
            <td><span id = "31" class='appoint'>31</span></td>
            <td><span id = "32" class='closed'>32</span></td>

JS:

            $("span[class='open'][class='appoint']").click(function() {

                alert($(this).html());

            });

I have tried below combinations too, but nothing seems to work.

$("span.open.appoint")
$("span .open .appoint")
$("span .open, .appoint")
2
  • click function not responding on any of the span elements after applying above class selectors...any ideas??? Commented Aug 11, 2015 at 9:50
  • Are these HTML-Code generated from Javascript / Jquery? Commented Aug 11, 2015 at 10:13

2 Answers 2

2

Problem with the code

$("span.open.appoint")

It selects appoint which has span and open in the same attribute list/node.

$("span .open .appoint")

Descendant selector, only when appoint is a child of open

$("span .open, .appoint")

Selects open only if it is a child of span

Solution:

Try with $("span.open, span.appoint")

You need to use multiple CSS selectors separated by ,

$("span.open, span.appoint").click(function() {
  $(this).css('background-color','lightblue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td><span id="28" class='open'>28</span>
</td>
<td><span id="29" class='open'>29</span>
</td>
<td><span id="30" class='closed'>30</span>
</td>
<td><span id="31" class='appoint'>31</span>
</td>
<td><span id="32" class='closed'>32</span>
</td>

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

4 Comments

I tried it, but click function is not at all working for any of the span elements.
If you check the output, it is working right? :) Seems like there are other problems to deal with.
I meant, check the output of my solution. It is working. There must be a problem with your existing code apart from this small portion. Conflicts maybe or the way you have included the script.
when I use $('span') it works, but after adding class names along with span as selector, click event doesn't work...
1

Use Multiselector in jquery

$("span.open, span.appoint").click(function() {
      alert($(this).html());
 });

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.