3

syntax error, unrecognised expression: #2015-11-30|1112|1

I have an anchor tag with an Id of '2015-11-30|1112|1' that I would like to apply a class to. I am doing the same method for on a '' and this works, but I am getting syntax errors with the following. Can anyone explain the syntax error?

   $(document).ready(function() {
        $("#tbl_calendar").on("click", "a", null, clickAppointment);
    });


function clickAppointment(eventData)
    {
        //Get the Id of the appointment that has been clicked:
        currentAppointment = $(this).attr('id');

        //alert('clicked' + '#'+currentAppointment)

        $('#'+currentAppointment).addClass('selected');
    }
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
japes Sophey
  • 487
  • 3
  • 8
  • 26
  • 2
    What's the `null` doing there? Change it to `$("#tbl_calendar").on("click", "a", clickAppointment);`, if you're not passing data, no need to use that argument – adeneo Dec 06 '15 at 22:49
  • 3
    Why not just `$(this).addClass('selected');`? You're trying to select an element with the same `id` as the clicked element. If an `id` is unique, that doesn't make sense. – Josh Crozier Dec 06 '15 at 22:51
  • 1
    Also have a look at [this question](http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html) for valid characters for IDs. – Quantumplate Dec 06 '15 at 22:55

2 Answers2

4

You should escape the special chracters in your id using \\, check example bellow.

Hope this helps.


console.log( $("#2015-11-30\\|1112\\|1").text() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="2015-11-30|1112|1">Div text example</div>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
2

For your current code to work, you don't have to use that id selector since you already have the reference of the object inside the event function.

$(document).ready(function() {
  $("#tbl_calendar").on("click", "a", clickAppointment);

  function clickAppointment(eventData) {
    //"this" will have a reference to the clicked object
    $(this).addClass("selected");
  }
});

Not sure about your HTML, but considering something similar to the below one.

<ul id="tbl_calendar">
  <li>
    <a id="2015-11-30|1112|1">Click</a>
  </li>
</ul>

Working sample

rahul
  • 184,426
  • 49
  • 232
  • 263