Select all the same elements of the class and save in the line

I have a page on which there are comments left by users, each message has its own identifier, which is stored in a hidden input tag, to dynamically receive the latest messages that I need, in order to know the identifier of all messages and place them in a line, each identifier should be separated by a comma.

eg...

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

currently the ignoreMessagesColl variable only finds the first instance of the .activityid class that has a value of "579", but I really need to ignore the MessageColl to have a value of "579, 578, 577"

+4
source share
4 answers

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

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

What does it do:

  • map goes through all the matched elements and builds an array of jQuery from which the iterator function is returned.

  • get gets the base array from the jQuery shell (I have no idea why map returns a jQuery wrapper).

  • join joins the elements of the array into a string delimited by this separator.

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

+12
source
 var values = []; $('.msgContainer input.activityId').each(function(){ values.push($(this).val()); }); console.log(values); 
+2
source

You must have:

 var arr = [], str; $("input.activityId").each(function(){ arr.push(this.value); }); str = arr.join(','); 
+2
source
 var ignoreMessagesCol = $("input.activityId").map(function() { return $(this).val(); }).get().join(", "); 

.map () will execute an internal anonymous function for each selector element and return a collection of jQuery objects ..get () will make an array..join () make it a comma separated string

+1
source

Source: https://habr.com/ru/post/1393123/


All Articles