okezumi
okezumi

Reputation: 45

How to generate sequence number with jquery?

I had someone who did this script (credit Chyno Deluxe) that generate a list of menu whatever we write on the box, the question is, I need to generate a sequence of number that continuously added to it

here is the example needed,

<li id='item1'></li> <li id='item2'></li> <li id='item3'></li> <li id='item4'></li>

the number generated beside item'#' , 1,2,3,4,5,6

I had this that generate number, but it was fixed number, here

$.map($(Array(8)),function(val, i) { return i; })

this one only make like this

1,2,3,4,5,6,7,8

the script

(function($) {
        "use strict";
        var t2h = {
                buildHTML: function() {
                        var i, list, type = this.htmlSelect.options;
                        if (type[1].selected) {
                                //console.log(type[1].text);
                                list = "<select>";
                                list += "\n";
                                for (i = 0; i < this.get_items().length; i++) {
                                        list += "  <option>";
                                        list += this.get_items()[i];
                                        list += "</option>";
                                        list += "\n";
                                }
                                list += "</select>";

you can see the demo below with jquery code that will generate

<select>
<option>menu 1</option>
<option>menu 2</option>
</select>

I need to improve it by adding tag id='' + number on it, like this

<select>
<option id='item1'>menu 1</option>
<option id='item2'>menu 2</option>
</select>

demo : [a link] http://codepen.io/diden/pen/YwwVKO

Hope I can get help with this here, Thank you guys :)

Upvotes: 4

Views: 2919

Answers (2)

Gregg Duncan
Gregg Duncan

Reputation: 2725

concatenate "item" with the iterator of your for loop plus one (i + 1). and set that as the id while looping through the items. (Note that i starts at zero so if you want it to start with 1 then you have to add 1 to it)

Upvotes: 0

juvian
juvian

Reputation: 16068

for (i = 0; i < this.get_items().length; i++) { // here i will go from 0 to the length of the items the select will have -1 
    list += "  <option>"; // for each of these values of i, we add the first part of the html to list, which is a string variable
    list += this.get_items()[i]; // this adds the ith text that the user wrote, but it´s 0 index based instead of starting with 1

So what you want is just add the id correlated to index of the line the user entered . And this is just i+1 !

So:

list += "  <option id='item"+(i+1)+"'>"; // we open open and close "" to add (i+1) which is a varibale, and its the id we wanted

Upvotes: 2

Related Questions