Good day to all. Asked to see the code in which there is one problem. In jQuery, I'm not really. There is a site, on it you carry out tasks, points are given for tasks. There are two divas with the same class .balance_num, in which points are displayed, after completing, a certain amount is added to these points, and the total amount is not displayed correctly in total.

_balance: funtion(n) { var points_a = $('.balance_num').text() * 1 //берется изначальное количество баллов var points_plus = points_a + (n * 1); //прибавляется баллы за задание $('.balance_num').text(points_plus); //вставляется обратно в оба div } 

It seems simple. But for example, if there were 12 points, for the task they added 3 points, and instead of 15 points, for some reason he inserts the number 1215.

Tell me where to dig?

  • $ ('. balance_num') is an array, maybe you should choose eq (0)? - Jean-Claude
  • at the end of .text (point_plus) missing the letter s - points_plus - Jean-Claude

2 answers 2

The problem is that you have duplicated classes for blocks. For calculations you need to take the value of only one block. Yes, and multiply by 1 makes no sense.

 _balance: funtion(n) { var points_a = parseInt($('.balance_num:first').text()); // приводим строку к числу, и берем значение с первого div'a var points_plus = points_a + (n); $('.balance_num').text(points_plus); } 

  • Yes, thanks, really, later I also thought that I should choose the first block. и в третей строке нужно (n * 1) - Endorphin
 _balance: function(n) { // Так как элементов с классом balance_num несколько, то нам нужно собрать их в массив для последующей обработки в цикле let divs = $('.balance_num'); // проходим в цикле по всем элементам с классом balance_num $.each(divs, function(i, div){ // Получаем содержащийся в элементе текст и приводим его к числу let points_a = parseInt($(div).text()); // Прибавляем нужное число, переданное в функцию аргументом let points_plus = parseInt(points_a + n); // Обновляем содержимое элемента $(div).text(points_plus); }); } 
  • He still inserts in both diva 1215 instead of 15. - Endorphin
  • he replaced parse by multiplication by one. '' + points_plus is nonsense. - Jean-Claude
  • Corrected the answer)) - yarkov_aleksei
  • Please try to write more detailed answers. I am sure the author of the question would be grateful for your expert commentary on the code above. - Nicolas Chabanovsky