-1

I am creating elements dynamically based on user input and a count is inremented which relates to the ID of the element. (Basically, every time the user adds an element the ID is element1, element2 etc.

I have an event listener for the elements and when it's clicked I want just the number of the element to be stored in the variable.

This is what I am trying currently but 'NaN' is returned:

var id = parseInt($(this).attr('id'), 10);

If it helps you understand, this is how the elements are being created:

$("<div />")
    .attr("id", "input" + listCount + "container")
    .attr("class", "inputContainer")
    .appendTo("#checkboxContainer");
Xander
  • 991
  • 1
  • 13
  • 32
  • 1
    Possible duplicate of [JavaScript get number from string](http://stackoverflow.com/questions/10003683/javascript-get-number-from-string) – rlemon Apr 27 '17 at 20:29
  • 1
    I would suggest not using the ID to encode information. Instead, add a `data-` attribute to include that information. For instance, use `.attr('data-index', listCount)` then use `$(this).attr('data-index')` to pull it out. – Heretic Monkey Apr 27 '17 at 20:30
  • `$(this).attr('id') == "input" + listCount + "container"` which is clearly not a number, what did you expect? – Jeremy Thille Apr 27 '17 at 20:31
  • Possible duplicate of [jquery get number from id](http://stackoverflow.com/questions/2427853/jquery-get-number-from-id) – Heretic Monkey Apr 27 '17 at 20:31
  • `var id = parseInt($(this).attr('id').replace(/[^0-9]/g, ''), 10);` – Gerardo Apr 27 '17 at 20:32

2 Answers2

1

You want parseInt($(this).attr('id').replace(/[^\d]/g, ''), 10)

bcherny
  • 3,072
  • 2
  • 27
  • 35
  • Thank you, will accept shorty :) I don't actually need the parseInt I just missunderstood what that function did. I thought it would turn any string with numbers in, into just the numbers – Xander Apr 27 '17 at 20:38
0

You could always use a data attribute to store and retrieve just the number.

$("<div />")
.attr("id", "input" + listCount + "container")
.attr("class", "inputContainer")
.data("index", listCount)
.appendTo("#checkboxContainer");

You can retrieve the value using $("div").data("index"). You can find out more here: https://api.jquery.com/data/