Navin Rauniyar
Navin Rauniyar

Reputation: 10525

how to get number from the id value?

I've the following html:

<button type="button" id="step-1">step1</button>
<button type="button" id="step-2">step2</button>
<button type="button" id="step-3">step3</button>
<button type="button" id="step-4">step4</button>

And I want to get the number from id like 1,2,3,4. So using like this:

$('[id^=step]').on('click',function(){
    var stepbg = parseInt($(this).attr('id'),10);alert(stepbg);
});

But it's alerting NaN. demo

Upvotes: 0

Views: 363

Answers (9)

CJ Ramki
CJ Ramki

Reputation: 2630

Instead of using $(this).attr('id') you can simply use this.id.

try like this,

$('[id^=step]').on('click', function () {
    var stepbg = parseInt(this.id.replace(/\D/g, ''));
    alert(stepbg);
});

SEE THIS FIDDLE DEMO

Upvotes: 2

Shijin TR
Shijin TR

Reputation: 7768

$('[id^=step]').on('click',function(){
    var stepbg = $(this).attr('id').split('-');
    alert(stepbg[1]);
});

FIDDLE DEMO

Upvotes: 0

Sudharsan S
Sudharsan S

Reputation: 15393

Use split() in jquery.

    $('[id^=step]').on('click',function(){
    var stepbg = parseInt($(this).attr('id').split("-")[1] ,10);
        alert(stepbg);
   });

Fiddle

Upvotes: 0

Systematix Infotech
Systematix Infotech

Reputation: 2365

Try the code given below:

   $('[id^=step]').on('click',function(){
    var id =$(this).attr('id').replace(/step-/, '');
    alert(id)
});

Upvotes: 0

abc123
abc123

Reputation: 18763

jsFiddle Demo

Description: this is quick and dirty, I recommend using regex or split to get a better working example for production.

$('[id^=step]').on('click',function(){
    var stepbg = parseInt($(this).attr('id').substring(5), 10);
    alert(stepbg);
});

Upvotes: 0

Awlad Liton
Awlad Liton

Reputation: 9351

try split() this:

    arr = $(this).attr('id').split('-');//split to array
    stepbg = parseInt(arr[arr.length-1]); //get last element
    alert(stepbg);

demo

Upvotes: 0

Anant Dabhi
Anant Dabhi

Reputation: 11104

you can achive that using split()

$('[id^=step]').on('click',function(){
    var stepbg = parseInt($(this).attr('id').split("-")[1],10);alert(stepbg);
});

Also you can use replace function as well

$('[id^=step]').on('click',function(){
    var stepbg = parseInt($(this).attr('id').replace('step-',''));  alert(stepbg);
});

here is another regular expression example

 $('[id^=step]').on('click',function(){
var stepbg = parseInt($(this).attr('id').match(/\d+$/)[0], 10);  alert(stepbg);
    });

Upvotes: 1

Adil
Adil

Reputation: 148110

You can replace the string in the id with empty string you do not want and get the number out of it.

Live Demo

$('[id^=step]').on('click',function(){
    var stepbg = parseInt(this.id.replace('step-',''));  
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Try a simple regex to extract the last set of digits from the id

var stepbg = parseInt(this.id.match(/\d+$/)[0], 10);

Demo: Fiddle

Upvotes: 0

Related Questions