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

Creating a sticky header for a MatTable in Angular with horizontal scrolling

Having an issue with merging Sticky Column and horizontal scrolling. Check out this example (it's in Angular 8 but I'm using Angular 10). Link to Example The base example has sticky headers, so when you scroll the entire page, the headers stay ...

The Authorization header in POST and PATCH fetch requests is stripped by Typescript

I have developed an API in C# that utilizes JWT tokens for authorization. On the frontend, I store these tokens in local storage and retrieve them when making a request. GET or DELETE requests work seamlessly, as I can verify through console.log() that t ...

Get information from one div and implement it in a different div

I am working on an application that creates div boxes dynamically and loads images through AJAX to place inside these boxes. To avoid unnecessary loading, I want to check if a box already exists before loading images. If it does exist, then I would like t ...

Avoid causing the newline character to display

var i = 'Hello \n World' console.log(i) /* Output: Hello World */ /* Desired output: Hello \n world */ var j = 'javscr\u0012ipt' console.log(j) /* Output: javscr ipt */ /* Desired output: javscr\u0012ipt */ ...

Asynchronous task within an if statement

After pressing a button, it triggers the check function, which then executes the isReady() function to perform operations and determine its truth value. During the evaluation process, the isReady() method may actually return false, yet display "Success" i ...

I'm having trouble getting Stripe checkout to function properly with Angular 1.x

Utilizing the Stripe payment system for processing payments, I referenced a project on GitHub and a helpful blog. Incorporating nested views and routers in my project, the structure appears as follows: src app views controllers directives ...

Guide on sending a request to an API and displaying the retrieved information within the same Express application

I recently developed a basic express app with API and JWT authentication. I am now attempting to enhance the app by incorporating page rendering through my existing /api/.. routes. However, I am facing challenges in this process. app.use('/', en ...

Make sure to validate a form when submitting from an external source rather than through an HTML

In my form, there are various input fields (some acting as inputs even if they're not). Each field is validated upon submission by angular validation and html attributes like required, ng-maxlength, minlength, etc. Now, we want to implement a keyboar ...

I'm confused why this particular method within a class is not being inherited by the next class. Rather than seeing the expected extension, I am presented with - [Function (

Working fine with the Person class, the register() function displays the correct return statement when logged in the console. However, upon extending it to the Employee class, instead of the expected return statement, the console logs show [Function (anon ...

Safari is encountering an issue with the value provided for the width/height attribute in the <svg> element, as it is not a recognized

When adjusting the size of an SVG based on antd breakpoints, I encountered errors like these. I am passing props to an SVG element: const { lg } = useBreakpoint(); const height= lg ? "8rem" : xs ? "3rem" : "5rem"; const width ...

Display additional information upon hovering without disrupting the neighboring elements

When I hover over a component, I want to display more details and scale it up. However, this action ends up displacing the surrounding components. Take a look at the screenshot for reference: https://i.sstatic.net/ElXvk.jpg Below is the code snippet wher ...

When a JavaScript/jQuery open window popup triggers the onunload event after the about:blank page has been

Imagine you have a button that triggers a popup using window.open(): <button id = "my-button">Open window</button>​ You also want to detect when this popup window closes. To achieve this, you can use the following code: $('#my-button& ...

Ensuring the validity of input tags

I encountered an issue with an input tag that has a specific logic: https://codepen.io/ion-ciorba/pen/MWVWpmR In this case, I have a minimum value retrieved from the database (400), and while the logic is sound, the user experience with the component lea ...

Transform all the string data to integers in the JSON reply

Apologies for the basic question: This is the response I'm receiving: {id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "15487.0"} I want to convert rank: "1", price_usd: "15487.0" to rank: 1, price_usd: 15487.0 The reason beh ...

I duplicated a functional jQuery form and moved it to a different location, but I am only able to get the

I recently duplicated a jQuery form from one page to another, but encountered unexpected issues with the copied version. The original form functions as follows: An onclick function connected to an image triggers a confirmation modal window with an "OK" bu ...

The caption below the image is not functioning correctly when hovering over it

I'm having trouble getting the text to appear correctly underneath the image. Whenever I hover over the image, the text seems to overlap it. I am sure there is a simple solution to this issue, but I can't seem to figure it out. Removing the inlin ...

How to retrieve properties of the final item in an array using Vue.js

Struggling with Vue.js JavaScript implementation. This is the current code: <div id="app"> <h1>Items</h1> <div v-for="item in items"> <input v-model="item.val"> </div> <button @click="addItem"> Ne ...

Tips for creating an effective planar reflection using Open Graphics Library (OGL) in conjunction with a perspective camera

I'm attempting to create a mirror-like reflection of a WebGL scene on a plane using ogl, similar to how a mirror would behave. I tried implementing a basic version of the three.js reflector but ended up with a distorted image that doesn't accurat ...

Adjust the width of a DIV based on the content of other DIVs, and float and center them all

Initially, what seemed like a simple task has turned out to be more complicated than I anticipated. Here is my code: <html> <head> <style> div { border-top: 1px solid black; margin: 10px; } div#all { border: 0; } </style> <body ...

Does CSS have a selector that does not include any elements?

Considering the examples below <span id="foo_repeater_bar_0"></span> <span id="foo_repeater_batz_1"></span> I am looking for a CSS selector that will allow me to target only the elements whose id does not include foo_repeater. ...