How to select following input elements and how to get part of the ID using Jquery?
There are many input elements which IDs are
question5,question6, question7
,..., how to select these input elements using Jquery?
I do not mean $('#questio开发者_运维技巧n5')
, I mean to select the group of them.
Also How to get the the last number like 5,6,7,... using Jquery?
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
});
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));
});
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.
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
精彩评论