[Javascript] Addition de variable input

Résolu
Bonjour,

Tout d'abord voici mon code :
function processInput(obj_form)    
{    
 total=0;   
 for (i = 0; i < obj_form.length; i++)    
  {    
  if ( obj_form[i].value!='' )   
   if(isNaN(obj_form[i].value)==false)   
    total+=parseInt(obj_form[i].value);    
  }     
  document.formulaire_devis['tailles_devis_final'].value=total;   
}   


Voici ma fonction qui permet de calculer les variables saisie dans X champ input:
Supposons que l'on a 4 champs:
le résultat sera :
10+10+10+10=40 ici aucun problème

Par contre si je saisi
10+10+10+00010=38
Je ne vois vraiment pas d'ou venir ce problème.

Voici comment j'appel cette fonction sur mes champs input généré dynamiquement

onkeyup=\"this.value=this.value.replace(/[^0-9]/gi,'');processInput(document.formulaire_devis['tailles_devis[]']);\"


1 réponse

  1. Bonjour,

    il faut que tu précise en quelle base parseInt doit convertir la chaine de caractère passée en paramètre pour eviter tout problème avec les 0 devant tes nombres

    exemple

    <script type="text/javascript">
    
    document.write(parseInt("10") + "<br />");
    document.write(parseInt("10.33") + "<br />");
    document.write(parseInt("34 45 66") + "<br />");
    document.write(parseInt(" 60 ") + "<br />");
    document.write(parseInt("40 years") + "<br />");
    document.write(parseInt("He was 40") + "<br />");
    
    document.write("<br />");
    document.write(parseInt("10",10)+ "<br />");
    document.write(parseInt("010")+ "<br />");
    document.write(parseInt("10",8)+ "<br />");
    document.write(parseInt("0x10")+ "<br />");
    document.write(parseInt("10",16)+ "<br />");
    
    </script> 
    

    Valeurs :

    10
    10
    34
    60
    40
    NaN

    10
    8
    8
    16
    16

    Source : https://www.w3schools.com/jsref/jsref_parseInt.asp

    Adns
    1
    1. Je te remercie avec une base de 10 ça fonctionne parfaitement .

      Un grand merci à toi
      Sujet résolu =)
      0