sam
sam

Reputation: 13

Jquery get specific form elements by id into a string

i have a form that generates dynamic text inputs with ids like follows

<input id='item_blue_1' ... <input id='item_green_2' ... <input id='item_blue_3' ... <input id='item_green_4' ... <input id='item_blue_5' ...

how can i get all the values of only the elements that start with ids item_green, and put the values into a coma separated string or array, which ever is fastest and easiest?

Upvotes: 1

Views: 280

Answers (4)

Blazemonger
Blazemonger

Reputation: 92893

var arr = new Array();
$('input[id^="item_green"]').each(function() {
    arr.push($(this).val());
});
return arr; // or return arr.join(",") for a string

Upvotes: 2

Rafay
Rafay

Reputation: 31033

use start with selector

var arr=[];
var ids=$("[id^=item_green]");
arr = $.map(ids, function(n, index){
  return ($(ids).eq(index).val());
});

var stringArr=arr.join(","); //for string values

Upvotes: 1

Samich
Samich

Reputation: 30115

use following:

var joinedString = $('input[id^=item_green]').map(function(){
       return $(this).val();
    }).get().join(",");

http://jsfiddle.net/E86e5/3/

Upvotes: 1

Brian Glaz
Brian Glaz

Reputation: 15676

There are jquery selectors you can use to find elements that have attributes staring with a certain string. Here is an example:

var values = new Array();   
$('[id^=item_green]').each(function() { values.push($(this).val());});

Then values will be an array filled with all the values.

Upvotes: 0

Related Questions