Reputation: 1187
I have search jquery docs and SO but I can't find exactly what I am after.
I have spans created in php so they follow the pattern of:
<span class="om" id="o_1"></span>
<span class="om" id="o_3"></span>
...
I want to collect all the numbers in the id attribute and send them as an array of data (json if needs be) to the server via ajax and return the result to a function:
$.get("/pages/gOboxMeters", function($("span.om") <-- extract id's here ) {alert(data);} )
I am just alert
ing it for now.
What is the right code?
Thanks
Upvotes: 0
Views: 150
Reputation: 2921
You can also create an array
and push
in the value in that array with each
function of jQuery
var num = new Array;
$(".om").each(function(){
num.push($(this).attr("id").replace("o_",""));
$("#result").append($(this).attr("id").replace("o_","")+"<br>"); // just to show result visually
});
Upvotes: 1
Reputation: 148110
You can use map,
numbers = $('.om').map(function(){
return this.id.replace('o_', '');
}).get().join(',');
jQuery.get( "/pages/gOboxMeters", "yourVariable: " + numbers,
function(){alert(""sent);
});
You can use other delimiter character in join
Upvotes: 1
Reputation: 5213
You can use the .each()
jQuery function:
var arr = [];
$('span.om').each(function(index, item){arr.push($(item).attr('id').substring(2));})
In this very same page's console I tried the following, and it works right:
var arr = []
$('.mainnavs a').each(function(index, item){arr.push($(item).attr('id').substring(4));})
After this, use the arr variable for further processing.
Upvotes: 0
Reputation: 2604
You can collect and send the value like this
$(document).ready(function(){
var value = []
$('span.om').each(function(){
value.push($(this).attr('id'))});
alert(value);
$.get("/pages/gOboxMeters",{value : value }, function(){});
});
Example: http://jsfiddle.net/X5r8r/1120/
Upvotes: 0