ponzicoder
ponzicoder

Reputation: 25

Jquery: My onclick function for radio buttons not firing the first time a radio button is clicked

I want to ask the user a series of questions whose answers are radio buttons and with each answer update a the html of the id=creditamount with the variable creditAmount. My code only works after I've clicked the second radio button? Any ideas why that is happening?

<!DOCTYPE html>
  <html>
  <head>
    <script type="text/javascript" src="jquery-1.4.2.js"></script>
    <link rel = "stylesheet" type="text/css" href="custom.css" />

    <script>
    var creditAmount;
    $(document).ready(function(){

      $("input[name='alive']").live('click', function(){
        $("input").click(function() {

        creditAnswer = $(":checked").val(); 
        if (creditAnswer == "Yes")
            {
                creditAmount = 1000;
            }       
        else if (creditAnswer == "No")
            {
                creditAmount = 100;
            }       
        else if (creditAnswer == "Both")
            {
                creditAmount = 5000;
            }       
        $("#creditamount").html(creditAmount);
        });
     });            
      });
      </script> 

    </head>
    <form>
     <div id="creditlimit"> Credit Limit: </div><div id ="creditamount">0 </div>

    Are you currently alive? 
    <input type="radio" name="alive" value="Yes" /> Yes 
    <input type="radio" name="alive" value="No" /> No 
    <input type="radio" name="alive" value="Both" /> Depends upon the day of the week.
    </form>
    </html>

Upvotes: 0

Views: 1664

Answers (1)

Quincy
Quincy

Reputation: 4433

You only bind the actually business logic of the click event after the first click.

try

<script>
    var creditAmount;
    $(document).ready(function(){

      $("input[name='alive']").live('click', function(){

        creditAnswer = $(":checked").val(); 
        if (creditAnswer == "Yes")
            {
                creditAmount = 1000;
            }       
        else if (creditAnswer == "No")
            {
                creditAmount = 100;
            }       
        else if (creditAnswer == "Both")
            {
                creditAmount = 5000;
            }       
        $("#creditamount").html(creditAmount);



     });            
      });
      </script>

Upvotes: 1

Related Questions