0

I want to get the id from the parent element of a button, and the cut the text of. My guess was this:

HTML

<div id="test_4">
    <button id="button">Get ID</button>
</div>

JavaScript

$('#button').click(function() {
    parentID = $(this).parent().attr('id');
    newID = parseInt(parentID);

    alert(newID);
});

But that outputs NaN.

What is the right way to do this? fiddle

Emre Erkan
  • 8,433
  • 3
  • 48
  • 53
Legarndary
  • 957
  • 2
  • 16
  • 37

6 Answers6

4

There are many answers which use Regular Expressions but I don't recommend it. What you need is data- attributes. You use jQuery already so you can access your id with .data() method. Here is an example;

HTML

<div id="test_4" data-id="4">
<!--            ^^^^^^^^^^^^ this has to be added to use .data() -->
    <button id="button">Get ID</button>
</div>

JavaScript

$('#button').click(function() {
    var newID = $(this).parent().data('id');
    alert(newID);
});
Community
  • 1
  • 1
Emre Erkan
  • 8,433
  • 3
  • 48
  • 53
3
$('#button').click(function() {

    parentID = $(this).parent().attr('id');
    newID = +(parentID.match(/\d+/));

    alert(newID);
});

JSFiddle demo.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Hi James, just out of curiousity, what if the id had a value like `
    ` and would only want to return the digits `7824`, what's the Regex match?
    – chridam Feb 20 '14 at 08:52
1

Use a simple regex

$('#button').click(function () {

    var parentID = $(this).parent().attr('id');
    var newID = parentID.match(/\d+$/)[0];

    alert(newID);
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You can use regex to match the number inside your id string:

parentID = $(this).parent().attr('id').match(/\d+/);

Fiddle Demo

Felix
  • 37,892
  • 8
  • 43
  • 55
0

Try this :

$('#button').click(function() {

    parentID = $(this).parent().attr('id');

    newID = parseInt(parentID.split("_")[1]);

    alert(newID);
});

Demo : http://jsfiddle.net/3FZya/6/

Awlad Liton
  • 9,366
  • 2
  • 27
  • 53
-2
$('#button').click(function() {

    parentID = $(this).parent().attr("id");
    newID = parentID;

    alert(newID);
});

this will work

Prashobh
  • 9,216
  • 15
  • 61
  • 91
Nimmi
  • 1,997
  • 2
  • 12
  • 20