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,372
  • 3
  • 49
  • 53
Legarndary
  • 935
  • 1
  • 16
  • 36

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,372
  • 3
  • 49
  • 53
3
$('#button').click(function() {

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

    alert(newID);
});

JSFiddle demo.

James Donnelly
  • 122,518
  • 33
  • 200
  • 204
  • 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
  • 376,738
  • 64
  • 519
  • 520
0

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

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

Fiddle Demo

Felix
  • 37,443
  • 7
  • 40
  • 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,260
  • 2
  • 26
  • 50
-2
$('#button').click(function() {

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

    alert(newID);
});

this will work

Prashobh
  • 8,758
  • 14
  • 59
  • 90
Nimmi
  • 1,949
  • 2
  • 12
  • 20