user2239971
user2239971

Reputation: 13

jQuery loop through multiple items on page

So I have a page running countdown scripts in a table based on the time inside of a hidden input.

Each input has an individual id of "id="time_x" where x increases from 1.

Each on then runs the timer into a div .

My Question is how do I loop and select through a list of the inputs so that each input is able to feed the id to the jquery function which calls the timer.

Eg

<input ..... id="time_1" value="1000"/>
<input ..... id="time_2" value="2000" />

how can I select through all the inputs, get the value and then pass it to the right divs.

Thanks

Upvotes: 0

Views: 123

Answers (5)

Filippo oretti
Filippo oretti

Reputation: 49853

use a new element class for each one:

<input class="item" id="time_1" value="1000"/>
<input class="item" id="time_2" value="2000"/>
<input class="item" id="time_3" value="3000"/>

$.each($('.item'),function(){
 console.log($(this).attr('id')); 
});

or if you want to catch the input value is more easier:

$.each($('.item'),function(){
     console.log($(this).attr("value"));
    });

Upvotes: 2

bipen
bipen

Reputation: 36541

try this

$('input').each(function(v,i){
    console.log($(this).attr('id'));
});

NOTE: this will loop through all the inputs in the douments.. its better to give class to all the input you want to loop through and get its id

Upvotes: 2

Matteo Manchi
Matteo Manchi

Reputation: 354

Use "Start With" selector:

$('input[id^="time"]').each(function() {
   var value = $(this).val(); //get value

   //now get right div and inject value
   $(this).next('div').text(value);       
});

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173642

A non-jQuery solution:

var inputs = document.getElementsByTagName('input'),
id;

for (var i = 0; i < inputs.length; ++i) {
    id = inputs[i].id;

    if (id.indexOf('time_') == 0) {
        id = id.substr(5);
        // do stuff with id and inputs[i].value
    }
}

Upvotes: 1

drquicksilver
drquicksilver

Reputation: 1635

You can select all the inputs with an id of that form using $('[id^=time_]') as described in http://api.jquery.com/attribute-starts-with-selector/

You could call a function on these using .each() and you could get the ID of the current one by using this from inside the loop.

For a more specific answer you might need to ask a more specific question.

Upvotes: 1

Related Questions