Question

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

Was it helpful?

Solution 2

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

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

    alert(newID);
});

JSFiddle demo.

OTHER TIPS

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);
});

Use a simple regex

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

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

    alert(newID);
});

Demo: Fiddle

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

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

Fiddle Demo

Try this :

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

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

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

    alert(newID);
});

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

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

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

    alert(newID);
});

this will work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top