views:

92

answers:

4

There are many input elements which IDs are

question5,question6, question7

,..., how to select these input elements using Jquery?

I do not mean $('#question5'), I mean to select the group of them.

Also How to get the the last number like 5,6,7,... using Jquery?

+1  A: 

Try this:

$("input[id^='question']")

It will match input elements that have an id attribute that begin with question.

Once you have the elements, you can simply do a javascript substring on them to find the number:

$("input[id^='question']").each(function() {
    alert(this.id.substr(8));
});
zombat
These input elements are dynamically created.
Steven
That's fine, it won't make a difference. As long as they are part of the DOM, jQuery selectors will find them.
zombat
A: 

The easiest solution is probably to give the elements a common class that you can select:

<input id="question5" class="questions">
<input id="question6" class="questions">
<input id="question7" class="questions">

You cane then select all of them with $(".questions") and you can get their id:s with the jQuery .attr() function.

Emil Vikström
+2  A: 

You can select all the input elements whose its id starts with 'question', and then you can extract the number, eg.:

$('input[id^=question]').blur(function () {
  var number = +this.id.match(/\d+/)[0];
});

Just be careful because if the regular expression doesn't matchs, it will throw a TypeError, a safer version would be something like this:

$('input[id^=question]').blur(function () {
  var match = this.id.match(/\d+/);
  var number = match ? +match[0] : 0; // default zero
});
CMS
These input elements are dynamically created.
Steven
What can interfere the execution of this Jquery code?
Steven
A: 

add a class to each input field.

<input class='questions'>
$('.questions')

using the select method on the class will do the trick

depending on what you are trying to do, using the jQuery selector for the class you can add a .each to iterate through the array, like so.

$('.questions').each(function (i){  
  //i = the current question number
  alert('this is question '+i);
});

Also, here is further documentation on the .each method in jQuery

Derek Adair