$(function() { $(".test").click(function(){ var a=$("#l_inpt_1").val(); var b=$("#l_inpt_2").val(); var c=$("#l_inpt_3").val(); var sumS=(a+b+c)/3; $(".midle_g p").append(sumS); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" placeholder="Число 1" id="l_inpt_1"> <input type="text" placeholder="Число 1" id="l_inpt_2"> <input type="text" placeholder="Число 1" id="l_inpt_3"> <button class="test">Очистити поля</button> <div class="midle_g"> <p></p> </div> 

We have 3 inputs in them, we will enter the numbers 1,2,3 by pressing the button, we must find the average value (1 + 2 + 3) / 3 = 2, but the problem is that the sum displays as 123 and not 6 !How to fix!?

    1 answer 1

    Your fields were not added with numbers, but with text. ParseFloat turns text into number

     $(function() { $(".test").click(function(){ var a = parseFloat($("#l_inpt_1").val()); var b = parseFloat($("#l_inpt_2").val()); var c = parseFloat($("#l_inpt_3").val()); var sumS = (a+b+c)/3; $(".midle_g p").append(sumS); }); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" placeholder="Число 1" id="l_inpt_1"> <input type="text" placeholder="Число 1" id="l_inpt_2"> <input type="text" placeholder="Число 1" id="l_inpt_3"> <button class="test">Очистити поля</button> <div class="midle_g"> <p></p> </div> 

    • The jquery code doesn't work! - DarkAdmiral
    • @GenralSite, in a sense? Everything works for me - Yuri
    • replaced your code with you, when you press the button does not work! - DarkAdmiral
    • @GenralSite, then why does the code example work here? Have you provided a link to the library? - Yuri
    • 2
      @GenralSite, the answer works for me. Click: Run code and example will work. I don't know what's not working there - Yuri