开发者

jQuery: Give each form field a chronological increasing number

There is a dynamically generated form. For each form input field ('.questions'). I would like to show the number of the field(chronological). So the first field shows 1 the second 2 end so on.

I think I've almost got it in this code, but now it give for each element every number so input field one =1234 and two=1234 where it should be one=1 two=2.

$('.questions').each(function(index) {
     var num = index + 1;  
     ('<p class="开发者_JAVA百科num">'+num+'</p>').insertBefore('.questions'); 
});

now it works right:

$('.questions').each(function(index) {
     var num = index + 1;  
     ('<p class="num">'+num+'</p>').insertBefore(this); 
});


Or you can use

$('.questions').each(function(index) {
 var num = index + 1;  
 $('<p class="num">'+num+'</p>').insertBefore($(this));
});

The issue is that when you are using the insertBefore method, you are again selecting all the elements by using the '.questions' selector. Whereas you actually want to insert it just before the current element, which is represented by the $(this) jquery object.


The issue is with declaring the num inside the callback of each. Move the declaration of num to outside the callback.

Try this:

var num = 0;
$('.questions').each(function(index) {      
    num = index + 1;        
    $('<p class="num">'+num+'</p>').insertBefore(this);  
}); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜