Ways to save information using JavaScript by utilizing objects

I have created the following code:

$(".awesome").click(function () {
        var toStore = $("input[name=name]").val();
        if (/^[A-Za-z]+ [A-Za-z]+$/.test(toStore)) {
            $("#contain").children().fadeOut(1000);
            $("#contain").delay(1000).queue(function () {
                $("#contain").append("<h1>Welcome to My Quiz : " + toStore + "</br>" +
                    "You'll Get 10 Questions To Answer </br> " +
                    "Here Is the First One:Who is Prime Minister of the United Kingdom? </h1>");

                var allQuestions = [
                    {question: "Who is Prime Minister of the United Kingdom?",
                        choices: ["David Cameron",
                            "Gordon Brown",
                            "Winston Churchill",
                            "Tony Blair"],
                        correctAnswer: 0}
                ];
                $("#contain").append("<form><input type='radio' name='ans1' value='David Cameron'>David Cameron</br>" +
                    " <input type='radio' name='ans1' value='Gordon Brown'>Gordon Brown</br>" +
                    "<input type='radio' name = 'ans1' value = 'Winston Churchill' > Winston Churchill </br>" +
                    "<input type='radio' name='ans1' value='Tony Blair'>Tony Blair</br>" +
                    "<input type='submit' value='Submit' name='submit'></form>");
                $("input[name=submit]").click(function () {
                    var correctAnswer;
                    if ($("input[name=ans1]").val()) {
                        var x = "choices";
                        allQuestions[x] = "David Cameron";
                        for (var x in allQuestions) {
                            return correctAnswer = false;

                            if (allQuestions[x] === "David Cameron") {

                                return correctAnswer = true;
                            } else {
                                return correctAnswer = false;
                            }

                        }
                    }
                });
            });
        } else {
            alert("Please Input a Valid Name");
        }
    });
});

In this scenario, I have defined an Object named "allQuestions" with three properties: "question," "choices," and "correct answer." There is also a submit button that checks the input value under the name "ans1". If the answer is "David Cameron," the correctAnswer property will be updated to 1 instead of the initial value of 0. Suggestions on how to achieve this are welcome!

Answer №1

  • One issue is that direct event handling may not work with dynamically added elements if the event handler is registered before the elements are added. However, in this case, it seems to be functioning as you register the event handler after adding the elements. Consider changing it to:

    $("#contain").on("click","input[name=submit]", function(){ your function})

  • Another problem arises from accessing allQuestions incorrectly since it is an array. It should be referenced as: allQuestions[0][x];

  • The third issue relates to what @Benjamin Gruenbaum pointed out.

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

Extract the content from a widget on a different site

How can I eliminate the specified text shown in the image? https://i.sstatic.net/174fD.png This widget is sourced from an external website. Is it possible to use javascript to wrap a around the text and then remove it using css? It's important to ...

The state is not being processed properly

One challenge I am facing involves two components where a user can attach an image or gif to a post. When the image is clicked, a modal pops up and I aim to pass the data back to the modal so that the clicked image displays. To address this issue, I imple ...

Transform MVC4 model into a JavaScript JSON object within a cshtml file

I have a model on my cshtml page that I need to convert into a JSON object for use in the JavaScript on the same cshtml page. I am using MVC4. What is the best way to achieve this? ...

Tips on creating an inline editable cell in a Tree View

I've been working on a category tree that includes expand and collapse buttons. You can see what I have so far here: Category Tree Now, I'm looking to make each item inline editable. Can someone guide me on how to achieve this? If you want to t ...

How can I use Ajax code to send data to a PHP page and receive the results as a JSON-encoded multidimensional array containing information on each item?

Apologies for the unconventional question title. What I am trying to accomplish is managing two tables in my database: a hotel table (table1) and a room type table (table2). My goal is to allow customers to customize their travel packages by changing hote ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...

Implementing dynamic option selection in Vue using JavaScript and v-model

Is there a way to manage the chosen value in a v-modeled select tag using vue.js? I created a jsFiddle demonstration, but unfortunately, it is not functioning correctly. This leads to my inquiry: vm.$set('selected', '1') // does not wo ...

Transmitting data to a PHP script via AJAX and receiving a delayed response is not ideal for my needs

I am currently working on a contact page and have set it up to send a response if an invalid email is entered. However, the current code sends back an error message if a field is missing or left blank before clicking send. You can view the page at I still ...

React file viewer failing to display content via Firebase storage URLs

This code snippet is designed to display PDF files uploaded to Firebase storage using React. Here is a sample of the code: import ReactDOM from "react-dom"; import FileViewer from "react-file-viewer"; import "./styles.css"; ...

Vue.js template is failing to properly render hyperlinks, although basic string output is functioning as expected

Whenever I print attrib.link, everything works perfectly fine, <div v-for="attrib in attributes"> {{ attrib.link }} </div> However, when I try: <div v-for="attrib in attributes"> <a target='_blank' href={{ attrib.link } ...

Difficulty fetching css files on handlebars (express API)

Recently, I encountered an issue where the CSS styles were not being applied to my HBS code despite several attempts. The structure of my service is as follows: Service Controllers Models public css styles.css Routers Views index.hbs app.js pac ...

Retrieve mongodb objects that fall within a specified date range

Within my collection, there is an example document structured as follows: { "_id" : ObjectId("5bbb299f06229dddbaab553b"), "phone" : "+38 (031) 231-23-21", "date_call" : "2018-10-08", "adress_delivery" : "1", "quantity_concrete" : "1", ...

How to retrieve the total count of fields in AngularJS

Could you please specify the number of choices you would like to display? For example, if the user enters 10, then 10 choices will be displayed. I have been trying to implement this functionality, but it keeps resulting in a memory error. dynamicform.jsp ...

creating a value and finalizing on the yield operation

Despite my attempt to use es6 generators to set the value/done as I want, I am struggling to achieve the desired outcome. Whenever I try to set a value, it ends up in the "value" field, while the generator always returns "done: false" when I am actually ai ...

Implementing AJAX to dynamically update information based on user's selection from a dropdown

I need to dynamically adjust the opacity of my graph bars without requiring the user to manually refresh the page. I'm considering using AJAX for this purpose. How can I implement this functionality? const opacitySlider = document.getEle ...

PHP - JSON encoded string displaying object structure

I am struggling with an array structure, as confirmed by the print_r statement: Array ( [0] => Array ( [ads] => 343443543 [ad_name] => Cup [cup_id] => 8869327 [web_url] => www.yahoo ...

External website's Sharepoint modal dialog

Recently, I've been working with a Microsoft Sharepoint 2010 installation and noticed that when I search for items using the integrated search feature, the results contain a javascript call like this: <a id="SRB_g_b60c4a68_5348_49ec_846c_b9d069d67 ...

Utilizing the toggle switch functionality in Django with a boolean field implementation

My work_experience model includes an "is_working" field which is set to true when a user is currently employed at a company. I am using a toggle switch on the front end and would like to update the boolean field value for "is_working" with a click. What lo ...

What is the best way to execute two JavaScript functions within an inline onclick event?

I am currently working on the following code snippet: <script> function delay (URL) { setTimeout( function() { window.location = URL }, 2000); }</script> And then I have the following within the <body> element: <img src="small_rabbi ...

What is the best way to refresh my view after loading a new JavaScript file that is required to generate the correct HTML elements?

When I use $http.get() to retrieve my model $scope.workoutData, the object appears fine in the console.log(data) output. However, my view does not load as if it has received the model. Once the model is updated, I also need to trigger the owlCarousel() fun ...