user3683638
user3683638

Reputation: 25

filter function using match with regex

I am trying to get all the buttons that have id check-button_n being n in range 0 to 20 and perform click on them.

I used the following code for this:

$('button').filter(function () {this.id.match(/^check-button_/)}).click();

However it is not working. the match always returns null even though the id returns check-button_0, check-button_1, etc. Can anyone help me understand what I am doing wrong? Alternatively, can anyone tell me how to extract all buttons wit the matching id as explained before and perform click on them?

In tpl:

  Check Thanks!

I am new in javascript and jquery so detailed explanations would be appreciated! :)

Upvotes: 0

Views: 48

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

However it is not working. the match always returns null even though the id returns check-button_0, check-button_1, etc.

You need to return the matches in the filter's callback

$('button').filter(function () { return this.id.match(/^check-button_/)});

Or simply use the attribute starts-with selector ^=

$('button[id^="check-button_"]');

Alternatively, can anyone tell me how to extract all buttons wit the matching id as explained before and perform click on them?

$('button[id^="check-button_"]').each( function(){
   var id = +this.id.substring( "check-button_".length ); //13 is the length of `check-button_`
   if ( id >= 0 && id <= 20 )
   {
      $(this).click();
   }
})

Upvotes: 1

Related Questions