Is it possible to display this code through printing rather than using an onclick event?

I have a puzzle website in the works where users select a puzzle to solve. I am looking for a way to display the puzzles directly on the website instead of using pop-up boxes. I am proficient in various coding languages, so any solution will work for me.

Here is the code snippet I have currently:

<body>

<script type="text/javascript">

function myFunction()
{

        function ask() {
    var a = (Math.round(Math.random()*1000000))
    alert (a)
    return prompt("What was the number?") == eval( a );
}

var questions = [ask(), ask(), ask(), ask(), ask()],
    total = questions.length,
    correct = questions.filter(Boolean).length;

alert( "You got "+correct+"/"+total+" correct");

}

</script>

<button onClick="myFunction()">Remember the number</button>


</body>

<body>

<script type="text/javascript">
function myFunction2(){

        function ask() {
    var a = Math.floor(Math.random() * 10) + 1;
    var b = Math.floor(Math.random() * 10) + 1;
    var op = ["*", "+", "/", "-"][Math.floor(Math.random()*4)];
    return prompt("How much is " + a + " " + op + " " + b + "?") == eval( a + op + b);
}

var questions = [ask(), ask(), ask(), ask(), ask()],
    total = questions.length,
    correct = questions.filter(Boolean).length;

alert( "You got "+correct+"/"+total+" correct");
}
</script>

<button onClick="myFunction2()">Quick math</button>

</body>

</html>
</html>

I am seeking help to find a way to display this code as text within a text box on the page, allowing users to input their answers directly on the website. Any suggestions on how to enhance the design and functionality are welcome. Thank you!

Your assistance is greatly appreciated. Thanks.

Answer №1

I followed your instructions for the "Remember the number" button click. Unfortunately, I didn't have enough time to work on the other task.

Here is the HTML code:

<body>

<button id="rmbrBtn">Remember the number</button>

</body>

<body>

<button id="quivkBtn">Quick math</button>
    <div id="question_area">

    </div>
</body>

</html>
</html>

And here is the JS & jQuery code:

$("#rmbrBtn").click(function()
{
    var questions = [];

    function checkAnswer (){
            total = questions.length,
            correct = questions.filter(Boolean).length;
        if(total < 5)
        {
            ask();
        }else{
            var answer = '<div>You got '+correct+'/'+total+' correct <input type="button" value="Ok" id="ansOk"/></div>';
            $("#question_area").append(answer);
            $("#ansOk").click(function(){
                $(this).parent().empty();
                $(this).parent().remove();
            });
        }
    }

    function ask() {
        var a = (Math.round(Math.random()*1000000));
        var viewNumber = '<div>'+a+'<input type="button" id="ok" value="OK"/>'+'</div>';

        var promptVal = '<div>Enter your value: <input type="text" id="ans" /> <input   type="button" id="prmtOk" value="Ok"/></div>';

        $("#question_area").append(viewNumber);

        $("#ok").click(function(){
            $(this).parent().empty();
            $(this).parent().remove();

            $("#question_area").append(promptVal);  

            $("#prmtOk").click(function(){
               var prmt = $("#ans").val();
               var addVal = prmt == a;
                questions.push(addVal);
                checkAnswer();
                $(this).parent().empty();
                $(this).parent().remove();
            });
        });
    }

    // Run the function.
    checkAnswer();
});

You can find an online solution at: JSFiddle

I apologize for not being able to provide comments or work on the additional task at this time.

I trust that you will be able to understand and complete the task without further assistance.

Answer №2

To easily update the content of your webpage, simply insert a div element at the beginning of your code and utilize jQuery's .html() function.

For example:

$('.header').html('You are absolutely right!');

Check out this demonstration on http://jsfiddle.net/AMISingh/8nWKD/3/

Answer №3

Using only JavaScript, you can achieve the same functionality without relying on JQuery.
http://jsfiddle.net/8nWKD/4/

<div id="header" class="header">This is the header</div>
<div class="button" onClick="test_click()"> Click me!</div>

Here's the corresponding JavaScript code:

function test_click()
{
  document.getElementById("header").innerHTML = "CORRECT!";   
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting issue: JSON.stringify function returning 'undefined'

Having some trouble with JSON in JavaScript. I've been using JSON.stringify without issue until now. But suddenly, when I try to use it in my application, I keep getting this error in the console (Google Chrome): Uncaught TypeError: undefined is not ...

I'm currently working with ReactJS and attempting to retrieve JSON data from a REST API in JIRA, but I'm facing challenges in achieving this

I've been struggling for hours trying to understand why I am unable to access and transfer data in my array from the JSON data in JIRA using the REST API. Basically, I am attempting to retrieve the JSON data from the JIRA website via URL with Basic Au ...

Table-styled div containing a horizontal scrolling div

I am currently in the process of developing a webpage with dual columns. The two columns are segregated into div containers, one labeled right and the other labeled left. These columns reside within a parent div called row, which is nested within a main di ...

Unable to retrieve an image from various sources

My setup includes an Express server with a designated folder for images. app.use(express.static("files")); When attempting to access an image from the "files" folder at localhost:3000/test, everything functions properly. However, when trying to ...

What order should jquery files be included in?

Today I ran into an issue while trying to add datepicker() to my page. After downloading jqueryui, I added the scripts in the following order: <script type="text/javascript" src="js/jquery.js"></script> <script src="js/superfish.js">< ...

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

Storing Multi-Dimensional Arrays in Phonegap 1.0 for iOS 4.3+: A Comprehensive Guide

Working on a new iOS App built with HTML/CSS/JS(jQuery) + PhoneGap, I'm in need of loading a specific set of default records into local storage every time the application is opened. These records consist of multiple steps, each containing five sub-ste ...

Store the response data in a global variable or forward it to another function in Node.js using Express JS

I'm currently working on a function that makes a post request to an API (app.post), sending a token and a URL for redirection to webpay. The challenge I'm facing is saving that token in a global variable so that it can be accessed by another func ...

Displaying negative values highlighted in red on Datatables platform

After successfully integrating the datatables on my VF page, I now have one final requirement: to display any negative values in red and bold within numerical columns. In my Salesforce implementation, I am using <apex:datatable> for my table. Each nu ...

PHP loaded HTML does not allow JavaScript to execute

My system includes an announcements feature where all announcements are retrieved from a database and displayed on the screen using Ajax and PHP. Below is the code snippet used to load each announcement onto the page: echo '<div id="announcements ...

Is it possible to combine the index page with the login page for a web project, or is it recommended to create a separate login page?

Would it be a violation of any rules if the index page of my web project is used as the login page for users? Do I have to redirect them to a different page? Is this considered best practice? ...

Using jQuery to reference a specific div and the ID within that div

Is there a way to track when a link is clicked and reference an ID as a variable within the link? For example, if I have a link like this: <a class="TrackClick" id="SomeUnknownVar" href="javascript:void(0)" onClick="window.open('http://someurl&apo ...

What is the best way to create a footer in this scenario and is there a method to perfectly center an

What is the best way to position the footer at the bottom of the page without overlapping the top content? Is there a method to center both the height and width of the header element on the page? Can you review the layout of this webpage and provide feed ...

Injecting AngularJS directives and styling elements into the body section of a Twig template using the {% block body %} tag

I'm currently in the process of constructing a Rest API using Symfony 3 and Fosresbundle, with AngularJS responsible for fetching JSON data within twig templates. However, I've encountered an issue where I need to specify angularJS directives an ...

What is the best way to ensure the menu background aligns perfectly with the header in HTML/CSS?

Issue: Menu background doesn't align with header. (visible in the image provided below) VIEW IMAGE Any suggestions on how to resolve this alignment problem? CSS CODE : .header { margin:0px auto; max-width: 960px; } #header { height:30 ...

Encountering a fragment error while utilizing create-react-library

Recently, I embarked on the journey of publishing a React component to npm that I had created. In my quest for knowledge, I stumbled upon create-react-library, which I decided to use for the first time. As I started testing my component from the test folde ...

Javascript: Dynamically Altering Images and Text

One feature on my website is a translation script. However, I'm struggling to activate it and update the image and text based on the selected language. This is the code snippet I am currently using: <div class="btn-group"> <button type ...

Create a compressed package of a Vue project that can easily be inserted into a Blogger blog post as a single HTML file

Is there a way to package all the files related to a Vue.js project (HTML, JavaScript, CSS) into one single HTML file for easy deployment on a Blogger Blogspot post? In the past, a question similar to this was asked regarding bundling files into a single ...

Having trouble with jQuery show/hide not functioning properly?

My website has a sub-menu section with a shopping cart icon. When a user hovers over the icon, it reveals a hidden cart section. The user can then move the mouse into the cart section to remove items. The problem I'm facing is that if a user displays ...

Unforeseen box model quirks found in modern browsers when styling <table> elements

Here is a sample HTML document that demonstrates the issue: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; ...