IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Calculateur par checkbox


Sujet :

JavaScript

  1. #1
    Candidat au Club
    Femme Profil pro
    Enseignant
    Inscrit en
    Mars 2016
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 34
    Localisation : Suisse

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Mars 2016
    Messages : 2
    Points : 3
    Points
    3
    Par défaut Calculateur par checkbox
    Bonjour à touts et toutes.
    Je suis une vraie débutante et je n'arrive pas à résoudre un problème qui doit être tout simple.
    J'aimerai faire fonctionner un calculateur qui additionne et soustrait en activant ou désactivant des checkbox
    Ci-dessous, mon script. Il fonctionne bien avec des espaces de texte, mais pas avec les checkbox...?
    Merci pour votre aide.
    Charline

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    /* This script is Copyright (c) Paul McFedries and 
    Logophilia Limited (http://www.mcfedries.com/).
    Permission is granted to use this script as long as 
    this Copyright notice remains in place.*/
     
    function CalculateTotal(frm) {
        var order_total = 0
     
        // Run through all the form fields
        for (var i=0; i < frm.elements.length; ++i) {
     
            // Get the current field
            form_field = frm.elements[i]
     
            // Get the field's name
            form_name = form_field.name
     
            // Is it a "product" field?
            if (form_name.substring(0,4) == "PROD") {
     
                // If so, extract the price from the name
                item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))
     
                // Get the quantity
                item_quantity = parseInt(form_field.value)
     
                // Update the order total
                if (item_quantity >= 0) {
                    order_total += item_quantity * item_price
                }
            }
        }
     
        // Display the total rounded to two decimal places
        document.getElementById("order_total").firstChild.data = "CHF" + round_decimals(order_total, 2)
    }
     
    function round_decimals(original_number, decimals) {
        var result1 = original_number * Math.pow(10, decimals)
        var result2 = Math.round(result1)
        var result3 = result2 / Math.pow(10, decimals)
        return pad_with_zeros(result3, decimals)
    }
     
    function pad_with_zeros(rounded_value, decimal_places) {
     
        // Convert the number to a string
        var value_string = rounded_value.toString()
     
        // Locate the decimal point
        var decimal_location = value_string.indexOf(".")
     
        // Is there a decimal point?
        if (decimal_location == -1) {
     
            // If no, then all decimal places will be padded with 0s
            decimal_part_length = 0
     
            // If decimal_places is greater than zero, tack on a decimal point
            value_string += decimal_places > 0 ? "." : ""
        }
        else {
     
            // If yes, then only the extra decimal places will be padded with 0s
            decimal_part_length = value_string.length - decimal_location - 1
        }
     
        // Calculate the number of decimal places that need to be padded with 0s
        var pad_total = decimal_places - decimal_part_length
     
        if (pad_total > 0) {
     
            // Pad the string with 0s
            for (var counter = 1; counter <= pad_total; counter++) 
                value_string += "0"
            }
        return value_string
    }
     
    function totalcheckbox() {
    document.checkbox.TOTAL.value = ''; //I set the value of all the checkboxes equal to nothing
    var total = 0;
    //For loop iterates through all the checkboxes. ++ adds one each time to i.
    for (i=0;i<document.checkbox.select.length;i++) {
          if (document.checkbox.select[i].checked) {
            total = total + parseInt(document.checkbox.select[i].value); //take whatever they selected and make it into an integer
          }
        }
    document.checkbox.TOTAL.value = total; //total value box equal to the sum
    }
    //-->
    </script><script language="JavaScript" type="text/javascript">
    <!--
     
    /* This script is Copyright (c) Paul McFedries and 
    Logophilia Limited (http://www.mcfedries.com/).
    Permission is granted to use this script as long as 
    this Copyright notice remains in place.*/
     
    function CalculateTotal(frm) {
        var order_total = 0
     
        // Run through all the form fields
        for (var i=0; i < frm.elements.length; ++i) {
     
            // Get the current field
            form_field = frm.elements[i]
     
            // Get the field's name
            form_name = form_field.name
     
            // Is it a "product" field?
            if (form_name.substring(0,4) == "PROD") {
     
                // If so, extract the price from the name
                item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))
     
                // Get the quantity
                item_quantity = parseInt(form_field.value)
     
                // Update the order total
                if (item_quantity >= 0) {
                    order_total += item_quantity * item_price
                }
            }
        }
     
        // Display the total rounded to two decimal places
        document.getElementById("order_total").firstChild.data = "CHF" + round_decimals(order_total, 2)
    }
     
    function round_decimals(original_number, decimals) {
        var result1 = original_number * Math.pow(10, decimals)
        var result2 = Math.round(result1)
        var result3 = result2 / Math.pow(10, decimals)
        return pad_with_zeros(result3, decimals)
    }
     
    function pad_with_zeros(rounded_value, decimal_places) {
     
        // Convert the number to a string
        var value_string = rounded_value.toString()
     
        // Locate the decimal point
        var decimal_location = value_string.indexOf(".")
     
        // Is there a decimal point?
        if (decimal_location == -1) {
     
            // If no, then all decimal places will be padded with 0s
            decimal_part_length = 0
     
            // If decimal_places is greater than zero, tack on a decimal point
            value_string += decimal_places > 0 ? "." : ""
        }
        else {
     
            // If yes, then only the extra decimal places will be padded with 0s
            decimal_part_length = value_string.length - decimal_location - 1
        }
     
        // Calculate the number of decimal places that need to be padded with 0s
        var pad_total = decimal_places - decimal_part_length
     
        if (pad_total > 0) {
     
            // Pad the string with 0s
            for (var counter = 1; counter <= pad_total; counter++) 
                value_string += "0"
            }
        return value_string
    }
     
    function totalcheckbox() {
    document.checkbox.TOTAL.value = ''; //I set the value of all the checkboxes equal to nothing
    var total = 0;
    //For loop iterates through all the checkboxes. ++ adds one each time to i.
    for (i=0;i<document.checkbox.select.length;i++) {
          if (document.checkbox.select[i].checked) {
            total = total + parseInt(document.checkbox.select[i].value); //take whatever they selected and make it into an integer
          }
        }
    document.checkbox.TOTAL.value = total; //total value box equal to the sum
    }
    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    <form action="" class="freemailform" method="post">
    <p><span style="font-size:smaller;">Veuillez vous assurer de fournir une adresse email valide, afin que nous puissions vous répondre dans les meilleures conditions.</span></p>
     
    <table align="left" height="526" width="63%">
    	<tbody>
    		<tr>
    			<td class="left" height="22" style="display:none" valign="middle" width="216"><span>subject:</span></td>
    			<td height="22" width="0"><input class="input text" name="subject" size="30" style="display:none" type="text" value="Demande offre" /></td>
    		</tr>
    		<tr>
    			<td class="left" height="35" valign="middle" width="216">&nbsp;</td>
    			<td height="35">&nbsp;</td>
    		</tr>
    		<tr>
    			<td bgcolor="#c0c0c0" class="left" width="216"><b>Quantité</b></td>
    			<td bgcolor="#c0c0c0"><b>Désignation</b></td>
    			<td bgcolor="#c0c0c0" style="text-align: right;"><b>Prix par pièces</b></td>
    		</tr>
    		<tr>
    			<td align="left" height="30" valign="middle" width="216"><input name="PROD_1_1" onselect="CalculateTotal(this.form)" type="checkbox" value="10.00" /></td>
    			<td height="30" valign="middle">Choice 1</td>
    			<td align="RIGHT" height="30" valign="middle">10.00</td>
    		</tr>
    		<tr>
    			<td align="left" height="30" valign="middle" width="216"><input name="PROD_2_1" onselect="CalculateTotal(this.form)" type="checkbox" value="20.00" /></td>
    			<td height="30" valign="middle">Choice 2</td>
    			<td align="RIGHT" height="30" valign="middle">20.00</td>
    		</tr>
    		<tr>
    			<td height="36" valign="middle" width="216">&nbsp;</td>
    			<td height="36" valign="middle">
    			<p align="right"><b>TOTAL</b></p>
    			</td>
    			<td height="36" valign="middle">
    			<p align="right"><span id="order_total" style="text-align: right; font-weight: 700;">CHF 0.00</span></p>
    			</td>
    		</tr>
    		<tr>
    			<td class="left" height="22" valign="middle" width="216"><span>Nom:</span></td>
    			<td height="22"><input class="input text" name="Nom" size="35" type="text" /></td>
    		</tr>
    		<tr>
    			<td class="left" height="22" valign="middle" width="216">Prénom:</td>
    			<td height="22"><input class="input text" name="Prenom" size="35" type="text" /></td>
    		</tr>
    		<tr>
    			<td class="left" height="22" valign="middle" width="216"><span>Adresse email:</span></td>
    			<td height="22"><input class="input text" name="email" size="35" type="text" value="" /></td>
    		</tr>
    		<tr>
    			<td class="left" height="22" valign="middle" width="216">Date d'arrivée<span style="font-size:smaller;">:&nbsp;&nbsp; (jj/mm/aaaa</span>)</td>
    			<td height="22"><font color="#000000" face="Verdana" size="3"><select name="Date_Arrivee_jour" size="1"><option value="0">0</option><option value="1">1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option><option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option><option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option value="28">28</option><option value="29">29</option><option value="30">30</option><option value="31">31</option></select><select name="Date_Arrivee_mois" size="1"><option selected="selected">0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option><option>11</option><option>12</option></select><select name="Date_Arrivee_Annee" size="1"><option selected="selected" value="2016">2016</option><option value="2017">2017</option><option value="2018">2018</option></select></font></td>
    		</tr>
    		<tr>
    			<td class="left" height="22" valign="middle" width="216">Nombre de personnes:</td>
    			<td height="22"><font color="#000000" face="Verdana" size="3"><select name="Nombre_personnes" size="1"><option selected="selected">0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option></select></font></td>
    		</tr>
    		<tr>
    			<td class="left" height="64" valign="middle" width="216"><span>Informations supplémentaires:&nbsp; </span></td>
    			<td height="64">
    			<p><textarea cols="20" name="message" rows="5" style="width: 310px; height: 64px;"></textarea></p>
    			</td>
    		</tr>
    		<tr>
    			<td class="left" height="19" width="216">&nbsp;</td>
    			<td height="19">[CAPTCHA]</td>
    		</tr>
    		<tr>
    			<td class="left" height="26" width="216">&nbsp;</td>
    			<td height="26"><input name="fmf_nonce" type="hidden" value="[NONCE]" /><input name="cmd" type="hidden" value="send_fmf" /><span><input class="submit" name="aaa" type="submit" value="Envoyer le message" /></span></td>
    		</tr>
    	</tbody>
    </table>
     
    <p>&nbsp;</p>
    <input name="verified" type="hidden" value="b9958a5d82" />&nbsp;<input name="verified" type="hidden" value="b9958a5d82" />&nbsp;</form>

  2. #2
    Membre à l'essai
    Profil pro
    Inscrit en
    Décembre 2006
    Messages
    27
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2006
    Messages : 27
    Points : 19
    Points
    19
    Par défaut
    bonjour,
    pour commencer, vous devriez modifier les checkboxs pour prendre en compte l'event onchange, a chaque fois que l'état de la checkbox changera (selectionnée ou déselectionnée), votre méthode CalculateTotal sera appellée:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    <input name="PROD_1_1" onchange="CalculateTotal(this.form)" type="checkbox" value="10.00" />
    En suite, dans la méthode CalculateTotal, il suffit de vérifier si la checkbox est sélectionnée pour ajouter ou non le prix au résultat final:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    // Is it a "product" field?
    if (form_name.substring(0,4) == "PROD" && form_field.checked) {
            ...fait le calcul...
    }

  3. #3
    Candidat au Club
    Femme Profil pro
    Enseignant
    Inscrit en
    Mars 2016
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 34
    Localisation : Suisse

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Mars 2016
    Messages : 2
    Points : 3
    Points
    3
    Par défaut Merci
    Votre intervention met fin à mon problème.
    Encore merci pour votre aide

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. desactiver formulaire par checkbox
    Par monforte dans le forum Général JavaScript
    Réponses: 25
    Dernier message: 27/11/2007, 18h51
  2. combobox.enable active par checkbox
    Par oscar.cesar dans le forum Macros et VBA Excel
    Réponses: 4
    Dernier message: 29/09/2007, 08h14
  3. Réponses: 11
    Dernier message: 10/04/2007, 07h02
  4. [MySQL] afficher tous les enregistrements sélectionnés par checkbox
    Par ph_anrys dans le forum PHP & Base de données
    Réponses: 1
    Dernier message: 21/03/2007, 12h28
  5. Trier données dans formulaire par checkbox
    Par Sofie109 dans le forum Access
    Réponses: 9
    Dernier message: 27/07/2006, 08h56

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo