Reputation: 10525
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
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);
});
Upvotes: 2
Reputation: 7768
$('[id^=step]').on('click',function(){
var stepbg = $(this).attr('id').split('-');
alert(stepbg[1]);
});
Upvotes: 0
Reputation: 15393
Use split() in jquery.
$('[id^=step]').on('click',function(){
var stepbg = parseInt($(this).attr('id').split("-")[1] ,10);
alert(stepbg);
});
Upvotes: 0
Reputation: 2365
Try the code given below:
$('[id^=step]').on('click',function(){
var id =$(this).attr('id').replace(/step-/, '');
alert(id)
});
Upvotes: 0
Reputation: 18763
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
Reputation: 9351
try split()
this:
arr = $(this).attr('id').split('-');//split to array
stepbg = parseInt(arr[arr.length-1]); //get last element
alert(stepbg);
Upvotes: 0
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
Reputation: 148110
You can replace the string in the id with empty string you do not want and get the number out of it.
$('[id^=step]').on('click',function(){
var stepbg = parseInt(this.id.replace('step-',''));
});
Upvotes: 0
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