Search code examples
jqueryidentifierlimits

JQuery Identifier Name Limitations


I have a button on my html page generated with php:

<button type="button" id="KREDI-CEKIM-TALEP-SIL-BUTTON-cYSDLtvqnA6U0z600fPJ4crsIwLLZGrJmLpRW/t/j2NUJH4E0S0+3a4U7xQZFsDQ7+PoFzBahrekLFFS4lsyJw==" class="btn btn-labeled btn-danger" data-loading-text="iptal ediliyor..."><span class="btn-label"><i class="glyphicon glyphicon-remove"></i></span>İptal Et</button>

<script>$('#KREDI-CEKIM-TALEP-SIL-BUTTON-cYSDLtvqnA6U0z600fPJ4crsIwLLZGrJmLpRW/t/j2NUJH4E0S0+3a4U7xQZFsDQ7+PoFzBahrekLFFS4lsyJw==').on('click',function(event){alert(1);KrediCekimTalepSilFunc('cYSDLtvqnA6U0z600fPJ4crsIwLLZGrJmLpRW/t/j2NUJH4E0S0+3a4U7xQZFsDQ7+PoFzBahrekLFFS4lsyJw==');});</script>

I'm writing an onclick event but it's generating error message below:

Uncaught Error: Syntax error, unrecognized expression:
#KREDI-CEKIM-TALEP-SIL-BUTTON-cYSDLtvqnA6U0z600fPJ4crsIwLLZGrJmLpRW/t/j2NUJH4E0S0+3a4U7xQZFsDQ7+PoFzBahrekLFFS4lsyJw==

Error appears when page is loaded, it's not on click.


Solution

  • It's not jQuery, it's CSS selector syntax that's the issue (because jQuery uses CSS selectors). The id value contains characters you can't use directly in a CSS id selector. You can either escape those characters, or use getElementById:

    $(document.getElementById('KREDI-CEKIM-TALEP-SIL-BUTTON-cYSDLtvqnA6U0z600fPJ4crsIwLLZGrJmLpRW/t/j2NUJH4E0S0+3a4U7xQZFsDQ7+PoFzBahrekLFFS4lsyJw==')).on('click', function(event){
        alert(1);
        KrediCekimTalepSilFunc('cYSDLtvqnA6U0z600fPJ4crsIwLLZGrJmLpRW/t/j2NUJH4E0S0+3a4U7xQZFsDQ7+PoFzBahrekLFFS4lsyJw==');
    });
    

    getElementById doesn't use CSS selectors, so CSS selector syntax doesn't come into it.

    But it would be better, probably, to use an id that sticks to the CSS rules. In a comment you've said:

    This id is generated based on a string included in database. I must hide it from user. When user clicks this button ajax post executes and sending this id. PHP page is decodes it again.

    In that situation, I'd use a data-* attribute, like this:

    <button type="button" id="my-button" data-key="cYSDLtvqnA6U0z600fPJ4crsIwLLZGrJmLpRW/t/j2NUJH4E0S0+3a4U7xQZFsDQ7+PoFzBahrekLFFS4lsyJw==" class="btn btn-labeled btn-danger" data-loading-text="iptal ediliyor..."><span class="btn-label"><i class="glyphicon glyphicon-remove"></i></span>İptal Et</button>
    

    Then

    $("#my-button").on('click', function(event){
        alert(1);
        KrediCekimTalepSilFunc($(this).attr("data-key"));
    });
    

    Note how I got the value to pass to KrediCekimTalepSilFunc from the data-key attribute so it doesn't have to be repeated. If you have several of these, you could use a class on the button, maybe even a delegated selector:

    $("selector-for-container").on('click', '.delete-button', function(event){
        alert(1);
        KrediCekimTalepSilFunc($(this).attr("data-key"));
    });