0

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 alerting it for now.

What is the right code?

Thanks

4 Answers 4

1

You can use map,

Live Demo

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

Sign up to request clarification or add additional context in comments.

2 Comments

I would do .replace(/[^0-9]/g, '') for extra robustness but +1. Also, the var keyword to avoid a global.
@karim79 so does the get function do the ajax? (do I put the url in there?) or do I just pass 'numbers' as the data? Excellent concise answer BTW
1

You can also create an array and push in the value in that array with each function of jQuery

See Demo

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
});

Comments

0

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/

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.