Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all same class elements and store in string

Tags:

html

jquery

ajax

I Have a page which has comments left by users, each post has has its own id which is stored in a hidden input tag, in order to dynamically get the latest posts I need to know the id's of all posts and place them in a string, each id needs to be separated by a comma.

for example...

HTML markup

<div class='msgPost'><div class='msgContainer'>
    <input class='activityId' type='hidden' value='579'>
    <span>
        <div class='name'>Bob</div>nm
    </span>
</div>

<div class='msgPost'><div class='msgContainer'>
    <input class='activityId' type='hidden' value='578'>
    <span>
        <div class='name'>Tom</div>4
    </span>
</div>

<div class='msgPost'><div class='msgContainer'>
    <input class='activityId' type='hidden' value='577'>
    <span>
        <div class='name'>John</div>123
    </span>
</div>

Jquery code

function getLatestActivities(){
   var ignoreMessagesColl = $("input.activityId").val();

   $.ajax({
      traditional: true,
      dataType: "json",
      type: "GET", url: "include/process.php", 

      data:{
         getLatestActivity: "true",
         toUser: "4",
         ignoreMessages: ignoreMessagesColl
      },

      success: function(data){
         $.each(data, function (i, elem) {
            $('.commentMessage').after(elem.value);
         });              
      }
   });   
}

at the moment the variable ignoreMessagesColl only finds the first class instance of .activityid which has the value "579", but i actually need ignoreMessageColl to have the value "579, 578, 577"

like image 348
mk_89 Avatar asked Jan 26 '12 09:01

mk_89


1 Answers

val only returns the first one's value, try map plus get plus join:

var ignoreMessagesColl = $("input.activityId").map(function() {
        return this.value;
    }).get().join(",");

What that does:

  1. map loops through all of the matched elements and builds a jQuery-wrapped array of whatever the iterator function returns.

  2. get gets the underlying array from the jQuery wrapper (I have no idea why map returns a jQuery wrapper).

  3. join combines the elements of the array into a string delimited with the given delimiter.

The end result for your example data is that ignoreMessagesColl will have "579,578,577".

like image 91
T.J. Crowder Avatar answered Oct 04 '22 06:10

T.J. Crowder