Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  188] [ 6]  / answers: 1 / hits: 23576  / 13 Years ago, tue, february 21, 2012, 12:00:00

I'm try to run this function, which grabs all the checked checkbox values in to a comma separated string, and converts , in to , , so it reads better. The problem is I'm getting a strange error:



$('.name_boxes').live('click', function() {
var all_boxes = $('.name_boxes');
var all_boxes_values = []
for (var i = 0; i < all_boxes.length; i++) {
if (all_boxes[i].checked) {
all_boxes_values.push(all_boxes[i].value)
}
}
var all_boxes_values_clean = all_boxes_values.replace(/,/g,, );
alert(all_boxes_values_clean);
});


The console error says:




Uncaught TypeError: Object Aaron Ramsey,Aaron Renfree has no method 'replace'.




I'm not getting the alert box.



This is a bit beyond me, can anybody explain what I'm doing wrong?


More From » typeerror

 Answers
8

Although alert(some_array) prints a string representation of the array, the array itself is not a string. Thus, it does not have .replace. alert is forced to convert it into a string because the alert box can only show characters.



You can simply join using a custom separator, though. join is a function of arrays:



var all_boxes_values_clean = all_boxes_values.join(, );


As a side note, I recommend console.log over alert because it:




  1. shows the actual object/array instead of a string representation (especially useful with objects instead of the useless [object Object] you receive with alert)

  2. frees you from closing the popup each time

  3. keeps track of other logs so that you have an actual log of logs


[#87310] Monday, February 20, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karyme

Total Points: 545
Total Questions: 102
Total Answers: 120

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
;