How to get result from button click to display on the same page using Javascript

时间:2016-02-13 16:40:27

标签: javascript button click innerhtml

I am writing a page that has the code for a function in a pre tag, a button below the raw code that will run the code. I am having trouble with displaying the result of the button on the same page. I know document.write() is probably the culprit but I'm unsure what to change it to. Thanks you for your time.

<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>             <title>Stack Overflow Question</title>


</head>

<body>
<div>

  <!-- Nav tabs -->
  <ul class="nav nav-tabs" role="tablist">

  <li role="presentation" class="active"><a href="#q3" aria-controls="q3" role="tab" data-toggle="tab">Q3</a></li>

  </ul>

  <!-- Tab panes -->
  <div class="tab-content">


   <!-- Question 3 Start -->
<div role="tabpanel" class="tab-pane tab-pane active" id="q3">
    <div class="row">
      <div class="col-md-12">

      </div>
      <div class="col-md-12">
          <!-- button -->  
        <button id="q3-button" class="btn btn-default" type="button">Question Three Solution</button>
      </div>
      <div class="col-md-12">
          <!-- result --> 
        <div id="q3-result"></div> 
      </div>
      </div>
  </div>



    <script>
        $(document).ready(function(){



        //Q 3
            function start(){
        var start = parseInt(prompt("How long would you like the side to be?"));
     if (isNaN(start)) {
            alert("That's not a number, please retry.");
            var start = prompt("Please re-enter a number.");
     }
 var str = " " + "<br>";

            for (var i=1; i<=start; i++){


            for(var j=1; j<=8; j++){

               if((i+j)%2==0){
                   document.write("#");
               }
                else{
                    document.write(" ");
                    }
            }



 document.write(str);
            }


            $("#q3-result").html(start);
        }


        $("#q3-button").on("click", function(){
        start();
        });


    //ends document ready function
        });


    </script>

    </div>
    </body>


     </html>

0 个答案:

没有答案