0

I'm using PHP8.1 and JQuery.

I have a script with several links that each have an id that is a digit only. i.e:

<a href="#" id="<?= $id ?>"><?= $student_name ?></a>

// <a href="#" id="99">Jane Doe</a>
// <a href="#" id="101">John Smith</a>

Using JQuery I want to know when one of these links is clicked. I'm trying to use a regular expression, but it is not working. I've tried a couple of variations on this, to no avail.

$('a[id^="\d"]').click(function(){
    alert("link with digit in id was clicked");
});

I find several posts on doing this when there is some text in the id as well, but none when the id is just a digit.

Thanks for any advice.

2
  • Add the click handler to a parent object and use the delegated event to handle it. Use the target property of the event object to determine which link was clicked. See developer.mozilla.org/en-US/docs/Learn_web_development/Core/… Commented Nov 15 at 20:28
  • There are best practices that you should know about: "The HTML specification, particularly older versions like HTML4, explicitly states that ID and NAME tokens must begin with a letter. While HTML5 is more lenient regarding the characters allowed within an ID, the rule about not starting with a number remains a best practice and is often followed for compatibility and clarity." Commented 2 days ago

1 Answer 1

1

You cannot use a regular expression in the CSS selector. You could instead handle clicks on all a elements that have an id attribute, and then use a regular expression in the handler to distinguish between the cases you want to deal with and the other ones. Example:

$('a[id]').click(function() {
    if (/^\d+$/.test(this.id)) {
        console.log("A link having only digits in its id attribute was clicked");
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<a href="#" id="99">This link has a numeric id</a><br>
<a href="#" id="9a9">This link does not have a numeric id</a>

Or you could do the filtering before attaching the handler, using jQuery's filter method:

$('a[id]').filter((_, {id}) => /^\d+$/.test(id))
          .click(function() {
              console.log("A link having only digits in its id attribute was clicked");
          });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<a href="#" id="99">This link has a numeric id</a><br>
<a href="#" id="9a9">This link does not have a numeric id</a>

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

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.