0

Simple question from a newbie to javascript / jQuery I cannot figure out. Maybe someone here can answer this.

Let's say I have a php script that loads thousands of rows and displays them one per line and each row has a userid associated with it.

Each row is displayed within a div andd each div has a unique id based on the userid.

So in my while loop I have

$id = "div${userid}";

then each line would be like

<div id='$id'>some info here </div>

My question is, if I were to trap for an onclick, normally I would

$('#div123').on('click', function() {
..
..
..

But since I don't know the names of the divs, how can I create at trap for an unknown?

$('#unknown').on('click', function() {
..
..
..

Thank you for taking the time to read this.

JT

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I'd recommend setting an attribute on the line, such as `
    info
    ` and then on the click access the attribute within the function with `$(this).attr("user-id")`. You could also just use the attribute `id` instead, but that has other properties in HTML. Then, for all divs, add a class to the user div such as `
    info
    ` and capture click with `$(".user-row").click`.
    – forrestmid Mar 18 '17 at 17:43
  • http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on – Brahma Dev Mar 18 '17 at 17:46

1 Answers1

0

You can find elements that start with a specific string. The code below will find any id that starts with div, for example <div id="div123">

$( "[id^='div']" )
Alex
  • 4,674
  • 5
  • 38
  • 59