4

Is there a way in jQuery to check if an ID value (Ex. id="number1") contains a number?

The idea would be:

if (ID has a number which will come from a variable) then do something.

this is what I came up with so far but it only works with the first div:

    $("#tabsstyle li a").bind("click", function () {
        var numSlide = $(this).attr("rel");
        if ($('#slidesContainer div').attr('id').match(numSlide) ) {
        $('#slidesContainer div').fadeIn();
}

numSlide will store a number coming from one of the 'a' clicked and check that number will be included in the id value of '#slidesContainer div', once that checked then the right div will fadeIn.

HTML structure below:

<div id="slidesContainer">
  <div id="n1" class="slide">
    <h2>Web Development Tutorial</h2>
    <p><button class="test">N1</button></p>

  </div>
  <div id="n2" class="slide">
    <h2>Grunge Brushes, Anyone?</h2>
    <p><button class="test">N2</button></p>

  </div>
  <div id="n3" class="slide">
    <h2>How About Some Awesome Grunge Textures?</h2>
   <p><button class="test">N3</button></p>
  </div>
  <div id="n4" class="slide">
    <h2>'Tis the End, My Friend.</h2>
    <p><button class="test">N4</button></p>
  </div>



</div>
Aessandro
  • 5,517
  • 21
  • 66
  • 139

3 Answers3

4
var id = $('#element').attr('id'); // #element will replace 
                                   // with your desired selector



id.match(/[0-9]/g)

Checking

if( id.match(/[0-9]/g) ) {
  // do something
}
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0

You can take a look at the following jquery plugin https://github.com/jquery/globalize

That handles "numbers" a number can be an integer or a decimal, and a decimal number has different representations based on the culture :)

thmsn
  • 1,976
  • 1
  • 18
  • 25
0

You can use javascript to build a function with test and a regular expression to check if a string contains a number.

 function hasNumber(t){
     //regular expression: /\d/g
     return /\d/g.test(t);
 }

And then use jQuery to check the value of the attribute id

 alert (hasNumber($('#checkMe').attr('id')))
KoU_warch
  • 2,160
  • 1
  • 25
  • 46