javascriptjqueryonclickdomready

Jquery set the initial value


Hope you can help me. How do I set the initial value of an element in Jquery/Javascript?

To explain my problem I've the following snippet. My snippet works as I want, but only after "onclick". When I load the page, it won't get the right value. In this case I want want to when I click "show Monthly" to appear 80€ and when I click show Annual to appear 800€. But it only works after I click, not when I load the page.

Thanks

//Trying to set the initial value
$(document).ready(function() {
    $(".teste").ready(function() {
       var initialVal = $(this).html();
 if(initialVal !== "Show Monthly"){
    jQuery(".amountMonth").hide();
    jQuery(".amountAnnual").show();
 }else{
    jQuery(".amountMonth").show();
    jQuery(".amountAnnual").hide();
 }    
    });  
});


//OnClick is working right
$(document).ready(function() {
    $(".teste").click(function(e) {
        e.preventDefault();
        var initialVal = $(this).html();
        if(initialVal !== "Show Monthly"){
            $(".showAnnualMonthly a").text("Show Monthly");
            $(".perYearMonth").text("per year");
            jQuery(".monthlyOptions").hide();
            $("#arrowUpDown").removeClass("icon-up-arrow-button");
            $("#arrowUpDown").addClass("icon-down-arrow-button");
            jQuery(".amountMonth").hide();
            jQuery(".amountAnnual").show();
        }
        else if (initialVal !== "Show Annual"){
            $(".showAnnualMonthly a").text("Show Annual");
            $(".perYearMonth").text("per month");
            jQuery(".monthlyOptions").show();
            $("#arrowUpDown").removeClass("icon-down-arrow-button");
            $("#arrowUpDown").addClass("icon-up-arrow-button");  
            jQuery(".amountMonth").show();
            jQuery(".amountAnnual").hide();
        }
    });
        
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="amount amountAnnual" style="display:none">Annual --> 600€</p>
<p class="amount amountMonth" style="dispay:none">Monthly--> 60€</p>

<p class="showAnnualMonthly" id="showMonthlyOpt">
  <a href="" style="border:0; text-decoration:none;" class="teste">Show Monthly
    <div class="row">
      <span id="arrowUpDown" class="icon-down-arrow-button changeArrow" style="color: rgba(0, 161, 204, 1); margin-bottom:30px; font-size:36px;"></span>
    </div>
  </a>
</p>


Solution

  • Just run the code that shows and hides the p elements inside $(document).ready() but outside the click handler. There is no need for the first $(document).ready() function; you can combine them into one.