3

I have a page with some billing info. I want to affect a div based on the values of other divs. But, there is no output in my desired div.

Below is what I have so far:

$(document).ready(function () {
    $(".content-wrapper.planwrapper").each(function() {
        var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢","");
        var newBill = eval(originalRate*500+5.95);
    });
    $(this).find(".estimatedbill-wrapper .term-description").replace($(this),'$newBill');
});

I'm pretty new to JS, so any help would be appreciated!

Edit: Here is the HTML for one of the divs I'm working with -

<div class="esco_electric">
    <div class="esco_lower-wrapper">
        <div class="esco_rates-list" id="electric_list">
            <div class="rate-item row-id-Electric-' . $oneplan->ProductId . '-' . $oneplan->UtilityID . ' color3" data-product-id="' . $oneplan->ProductId . '" data-utility-id="' . $oneplan->UtilityID . '" data-tpv-id="' . $oneplan->TPVTemplateID . '" data-utility-name="' . $oneplan->UtilityShortName . '" data-zone="">
                <!-- Price / Suffix / Plan Type -->

                <div class="rate-type rate-wrapper">
                    <div class="rate-price" style="position:relative;">
                        <div class="mobleft" style="margin-bottom: 0px;">Fixed Rate</div>
                        <div id="pricediv-Electric-1853-50" class="price v-ratePlanValue mobcenter" style="padding-top:5px;">7.4<span style="font-size:0.7em;">¢</span></div>
                        <div class="price-suffix v-rateMeasurementSuffix mobright">kWh </div>
                    </div>
                </div>

                <!-- Description Area -->
                <div class="rate-description description-wrapper">
                    <!-- Upper Description -->
                    <div class="description-text">
                        <div class="term-title">Term</div>
                        <div class="term-description">
                            6 Months </div>
                        <div class="description-contentpricediv-Electric-1853-50 v-ratePlanDescription">No Cancellation Fee </div>
                    </div>
                </div>
                <div class="rate-description estimatedbill-wrapper">
                    <div class="description-text">
                        <div class="estimatedbill-title">Estimated Bill</div>
                        <div class="term-description">
                            $148 </div>
                        <div class="v-ratePlanDescription howisthiscalculated" data-mfp-src="#howisthiscalculated-popover">
                            How is this calculated?
                        </div>
                    </div>
                </div>

                <style>
                    .description-contentpricediv-Electric-1853-50 {
                        margin-top: 19px;
                        text-align: center;
                        font-size: 16px !important;
                        color: #535353!important;
                    }
                </style>

                <!-- Action buttons -->

                <a id="selectrateid-Electric-1853-50" href="index.php?type=resi&amp;s=options_and_information&amp;plan=1853&amp;StartDate=12-May-2016">
                    <div class="selectplan">
                        <p>Select Plan</p>
                    </div>
                </a>
                <a class="rate-edit" href="#">
                    <img src="images/check.png">
                    <p>
                        Edit&nbsp;Plan
                    </p>
                </a>
            </div>
            <!-- end rateitem -->

            <div id="UDSDIVID-Electric-1853-50" data-alert="" class="alert-box radius infodiv">
                <div class="pdfdiv">
                    <a eslinktext="Datos de la Electricidad" eslinkurl="PDFTemplates/ResidentialContracts/EFLViewer.php?lang=es&amp;key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w" class="pdfcustom" href="PDFTemplates/ResidentialContracts/EFLViewer.php?key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w" target="_blank" style="color:#000000;"><img src="images/pdf.png" height="25" width="25"> Electricity Facts Label</a><br>
                    <a eslinktext="Terminos y Condiciones" eslinkurl="PDFTemplates/TermsofServices/TOS_TX_Spanish.pdf?key=c3RhdGU9VFgmcmF0ZT00LjEmdGVybT02JnBsYW5uYW1lPVRoaW5rIFNlY3VyZSA2" class="pdfcustom" href="PDFTemplates/contract_api/index.php/contract/TC/state/TX/customer_type/RESI/service/Electric?PlanName=Think+Secure+6&amp;ContractNumber=TBD&amp;ServiceAddress=&amp;Price=4.1&amp;ServiceCity=&amp;ServiceAddress2=&amp;ServiceState=&amp;ServiceZipCode=&amp;Term=6&amp;MonthEnding=November&amp;Timestamp=1463061182 " target="_blank" style="color:#000000;"><img src="images/pdf.png" height="25" width="25"> Terms of Service</a><br>
                    <a eslinktext="Sus Derechos como Cliente" eslinkurl="PDFTemplates/Contracts/TX_YRAC_Spanish.pdf" class="pdfcustom" href="PDFTemplates/Contracts/TX_YRAC.pdf" target="_blank" style="color:#000000;"><img src="images/pdf.png" height="25" width="25"> Your Rights as a Customer</a><br><br>
                </div>
                <!-- end pdfdiv-->
                <div class="textrightdiv">Please contact Customer Care to request that a written copy of the terms of service document be sent to you by regular U.S. mail.<br><br><span style="padding-right: 30px;">Email Request: </span><a href="mailto:customercare@mythinkenergy.com">customercare@mythinkenergy.com</a><br><span style="padding-right: 25px;">Phone Request: </span>1-888-238-5610<br><a class="small button spanishButton" name="btnshowspanish" id="btnshowspanish22422" onclick="showspanishcontracts('btnshowspanish22422');">Documentos en Español</a></div><a onclick="$('#UDSDIVID-Electric-1853-50').hide();" style="display: none; padding: 10px;color:#000000;cursor: pointer; cursor: hand;position: absolute;top: 10px; right: 10px;">X</a>
                <div style="clear: both;"></div>
            </div>
        </div>
    </div>
</div>
angelcool.net
  • 2,505
  • 1
  • 24
  • 26
JB Everett
  • 43
  • 6

2 Answers2

2

Your logic is correct, while your code is incorrect, there are several mistakes that needs to be fixed:

  • There's no need to use eval, it has no effect in your code and it's better to avoid its use.

  • To use the variable newBill you don't need to write $newBill and if you put it inside '' it will be interpreted as string and simply printthe sentence$newBill`.

  • And in your case you declared the variable newBill inside .each function so it will be undefined outside this function scope so you can't use it outside of it, you need to declare it outside it.

  • And the use of $(".content-wrapper.planwrapper").each(function() { is unnecessary in your case and will break your code.

  • And You are using .replace() in the wrong place, to change the content of a div use .text(content) and not .replace().

This is how should be your code:

$(document).ready(function() {
  var newBill = 0;
    var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢", "");
    newBill = parseFloat(originalRate) * 500 + 5.95;
  $(this).find(".estimatedbill-wrapper .term-description").text(newBill);
});

THis is a working DEMO:

$(document).ready(function() {
  var newBill = 0;
  var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢", "");
  newBill = parseFloat(originalRate) * 500 + 5.95;
  $(this).find(".estimatedbill-wrapper .term-description").text(newBill);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="esco_electric
                   ">
  <div class="esco_lower-wrapper">
    <div class="esco_rates-list" id="electric_list">
      <div class="rate-item row-id-Electric-' . $oneplan->ProductId . '-' . $oneplan->UtilityID . ' color3" data-product-id="' . $oneplan->ProductId . '" data-utility-id="' . $oneplan->UtilityID . '" data-tpv-id="' . $oneplan->TPVTemplateID . '" data-utility-name="' . $oneplan->UtilityShortName . '"
      data-zone="">
        <!-- Price / Suffix / Plan Type -->

        <div class="rate-type rate-wrapper">
          <div class="rate-price" style="position:relative;">

            <div class="mobleft" style="margin-bottom: 0px;">Fixed Rate</div>


            <div id="pricediv-Electric-1853-50" class="price v-ratePlanValue mobcenter" style="padding-top:5px;">7.4<span style="font-size:0.7em;">¢</span>
            </div>



            <div class="price-suffix v-rateMeasurementSuffix mobright">
              kWh</div>
          </div>
        </div>

        <!-- Description Area -->
        <div class="rate-description description-wrapper">
          <!-- Upper Description -->
          <div class="description-text">
            <div class="term-title">Term</div>
            <div class="term-description">
              6 Months</div>
            <div class="description-contentpricediv-Electric-1853-50 v-ratePlanDescription">

              No Cancellation Fee</div>
          </div>
        </div>
        <div class="rate-description estimatedbill-wrapper">
          <div class="description-text">
            <div class="estimatedbill-title">Estimated Bill</div>
            <div class="term-description">
              $148</div>
            <div class="v-ratePlanDescription howisthiscalculated" data-mfp-src="#howisthiscalculated-popover">
              How is this calculated?
            </div>
          </div>
        </div>

        <style>
          .description-contentpricediv-Electric-1853-50 {
            margin-top: 19px;
            text-align: center;
            font-size: 16px !important;
            color: #535353!important;
          }
        </style>

        <!-- Action buttons -->

        <a id="selectrateid-Electric-1853-50" href="index.php?type=resi&amp;s=options_and_information&amp;plan=1853&amp;StartDate=12-May-2016">
          <div class="selectplan">
            <p>Select Plan</p>
          </div>
        </a>


        <a class="rate-edit" href="#">
          <img src="images/check.png">
          <p>
            Edit&nbsp;Plan
          </p>
        </a>
      </div>
      <!-- end rateitem -->

      <div id="UDSDIVID-Electric-1853-50" data-alert="" class="alert-box radius infodiv">
        <div class="pdfdiv">
          <a eslinktext="Datos de la Electricidad" eslinkurl="PDFTemplates/ResidentialContracts/EFLViewer.php?lang=es&amp;key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w"
          class="pdfcustom" href="PDFTemplates/ResidentialContracts/EFLViewer.php?key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w" target="_blank" style="color:#000000;">
            <img src="images/pdf.png" height="25" width="25">Electricity Facts Label</a>
          <br>
          <a eslinktext="Terminos y Condiciones" eslinkurl="PDFTemplates/TermsofServices/TOS_TX_Spanish.pdf?key=c3RhdGU9VFgmcmF0ZT00LjEmdGVybT02JnBsYW5uYW1lPVRoaW5rIFNlY3VyZSA2" class="pdfcustom" href="PDFTemplates/contract_api/index.php/contract/TC/state/TX/customer_type/RESI/service/Electric?PlanName=Think+Secure+6&amp;ContractNumber=TBD&amp;ServiceAddress=&amp;Price=4.1&amp;ServiceCity=&amp;ServiceAddress2=&amp;ServiceState=&amp;ServiceZipCode=&amp;Term=6&amp;MonthEnding=November&amp;Timestamp=1463061182 "
          target="_blank" style="color:#000000;">
            <img src="images/pdf.png" height="25" width="25">Terms of Service</a>
          <br>
          <a eslinktext="Sus Derechos como Cliente" eslinkurl="PDFTemplates/Contracts/TX_YRAC_Spanish.pdf" class="pdfcustom" href="PDFTemplates/Contracts/TX_YRAC.pdf" target="_blank" style="color:#000000;">
            <img src="images/pdf.png" height="25" width="25">Your Rights as a Customer</a>
          <br>
          <br>
        </div>
        <!-- end pdfdiv-->
        <div class="textrightdiv">Please contact Customer Care to request that a written copy of the terms of service document be sent to you by regular U.S. mail.
          <br>
          <br><span style="padding-right: 30px;">Email Request: </span><a href="mailto:customercare@mythinkenergy.com">customercare@mythinkenergy.com</a>
          <br><span style="padding-right: 25px;">Phone Request: </span>1-888-238-5610
          <br><a class="small button spanishButton" name="btnshowspanish" id="btnshowspanish22422" onclick="showspanishcontracts('btnshowspanish22422');">Documentos en Español</a>
        </div><a onclick="$('#UDSDIVID-Electric-1853-50').hide();" style="display: none; padding: 10px;color:#000000;cursor: pointer; cursor: hand;position: absolute;top: 10px; right: 10px;">X</a>
        <div style="clear: both;"></div>
      </div>
    </div>
  </div>
</div>
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

Check it out: https://jsfiddle.net/vmtzqnu0/5/

There are a few things to fix to get this working:

1. Your use of var

This keyword creates a variable within the code block (scope) that you use it, but outside of that block it's no longer usable. So when you say var newBill = ... inside the $.each() loop, you can't use it outside of there.

We can fix this by removing the keyword and (optionally) add the var newBill; statement just outside that block:

$(document).ready(function () {
    var newBill; // will be used later
    $(".content-wrapper.planwrapper").each(function() {
        var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢","");
        newBill = eval(originalRate*500+5.95);
    });
    $(this).find(".estimatedbill-wrapper .term-description").replace($(this),'$newBill');
});

2. Your use of eval()

You should probably just never use eval(). Moreover, it doesn't do what you think. You pass it a string of JS code and it will run that code. You don't pass it a statement.

So newBill = eval(originalRate*500+5.95); becomes newBill = originalRate*500+5.95;. You're best off wrapping that in parseFloat() too:

newBill = parseFloat(originalRate) * 500 + 5.95;

3. Your use of $.replace()

Here you actually want to use $.text() or $.html(). These functions are used to replace the content of an element. So, your final code will look like this:

$(document).ready(function() {
    var newBill;

    $(".content-wrapper.planwrapper").each(function() {
        var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢", "");
        newBill = parseFloat(originalRate) * 500 + 5.95;
    });

    $(this).find(".estimatedbill-wrapper .term-description").text(newBill)
});

4. There is no .planwrapper

Instead, loop through .v-ratePlanValue:

$(document).ready(function() {
    var newBill;

    $(".v-ratePlanValue").each(function() {
        var originalRate = $(this).text().replace("¢", "");
        console.log(this, originalRate);
        newBill = '$' + ((parseFloat(originalRate) * 500) + 5.95);
    });
    $(this).find(".estimatedbill-wrapper .term-description").text(newBill)
});

Good resources while learning Javascript, jQuery:

Community
  • 1
  • 1
xyhhx
  • 6,384
  • 6
  • 41
  • 64
  • Thank you! This is really helpful! However, when I checked the jsfiddle and ran it, the estimated bill didn't change. Is there something else I need to do? – JB Everett May 12 '16 at 16:24
  • I'm seeing $148 in the estimated bill portion. What are you seeing? – xyhhx May 12 '16 at 16:26
  • I'm seeing $148, as well. It should turn out to be 3705.95 (I know, it's outrageous, but I want to show something unreasonable so I can see the change). – JB Everett May 12 '16 at 16:30
  • Sorry about that! It's updated. There was no `.planwrapper` found so now it loops through all `$(".v-ratePlanValue")` instead – xyhhx May 12 '16 at 16:31
  • 1
    If you don't have multitple `.v-planRateValue` elements on the page, you don't need to loop through them. – xyhhx May 12 '16 at 16:33
  • @Martin Well pointed out, that's what I mentioned in my answer in fact I missed it in the first place, but in it's unecessary here. – cнŝdk May 12 '16 at 16:36
  • Yeah I left the loop in my answer because I'm not sure if this is exactly how it will render in production. – xyhhx May 12 '16 at 16:37