Using JavaScript functions on HTML data loaded by the jQuery.append() method: A guide

Utilizing JSON data, I have successfully generated HTML content representing Questions and Multiple Choice Questions. My next goal is to capture user responses in an array after the submit button is clicked. This involves storing which radio button the user has selected.

var obj = JSON.parse(
  '{"single": [{"id": 1,"question": "this is a question1?","option": ["option1","option2","option3","option4"]},{"id": 2,"question": "this is a question2?","option": ["option1","option2","option3","option4"]},{"id": 3,"question": "this is a question3?","option": ["option1","option2","option3","option4"]},{"id": 4,"question": "this is a question4?","option": ["optionu1","optionu2","optionu3","optionu4"]}],"multiple": [{"id": 1,"question": "this is a multiple question1?","option": ["optionm1","option2lj","option3","option4"]},{"id": 2,"question": "this is a multiple question2?","option": ["optionm1","option2j","option3","option4"]},{"id": 3,"question": "this is a multiple question3?","option": ["optionm1","option2gg","option3","option4"]},{"id": 4,"question": "this is a multiple question4?","option": ["optionm1","option2h","option3","option4"]}],"integer": [{"id": 1,"question": "this is a int question1?"},{"id": 2,"question": "this is a int question2?"},{"id": 3,"question": "this is a int question3?"},{"id": 4,"question": "this is a int question4?"}]}'
);
var s = [0, 0]; //only single correct;
var t = []; //only multiple choice
var u = []; //only numeric type
$(document).ready(function() {
});
function my(check, sub, err) {
  console.log(check + " " + sub + " " + err);
  var f = 0;
   if (document.getElementById("test" + check - 3).checked) {
    f = 1;
    s[0] = 1;
  } else if (document.getElementById("test" + check - 2).checked) {
    f = 1;
    s[0] = 2;
  } else if (document.getElementById("test" + check - 1).checked) {
    f = 1;
    s[0] = 3;
  } else if (document.getElementById("test" + check).checked) {
    f = 1;
    s[0] = 4;
  } else {
    $("#error" + err).show();
  }
  if(f===1){  
    document.getElementById("submit" + sub).disabled = true;
    $("#error"+err)
      .show()
      .text("Your answer has been successfully submitted.");
  }
}

function read() {
  var pages = obj.single;
  var x = 4; //for tests and creating new ID's
  var sub = 1; //for submission
  var err = 1; //for errors
  pages.forEach(function(page) {
    var test =
      "<div class='row'>" +
      "<div class='col s12 m12'>" +
      "<div class='card teal accent-1 hoverable' id='car'>" +
      "<div class='card-content  center-align'>" +
      "<span class='card-title'>" +
      "Question " +
      page.id +
      "</span>" +
      "<form action='#'>" +
      "<p>" +
      page.question +
      "</p>" +
      "<p><input name='group1' type='radio' id='test" +
      (x - 3) +
      "'/>" +
      "<label for='test" +
      (x - 3) +
      "'>" +
      page.option[0] +
      "</label></p>" +
      "<p><input name='group1' type='radio' id='test" +
      (x - 2) +
      "'/>" +
      "<label for='test" +
      (x - 2) +
      "'>" +
      page.option[1] +
      "</label></p>" +
      "<p><input name='group1' type='radio' id='test" +
      (x - 1) +
      "'/>" +
      "<label for='test" +
      (x - 1) +
      "'>" +
      page.option[2] +
      "</label></p>" +
      "<p><input name='group1' type='radio' id='test" +
      x +
      "'/>" +
      "<label for='test" +
      x +
      "'>" +
      page.option[3] +
      "</label></p>" +
      "</form>" +
      "<h6 id='error" +
      err +
      "'>Please select an option</h6>" +
      "</div>" +
      "<div class='card-action center'>" +
      "<button class='btn'  onclick='my(" +
      x +
      "," +
      sub +
      "," +
      err +
      ")' id='submit" +
      sub +
      "'>Submit</button>" +
      "</div>" +
      "</div>" +
      "</div>" +
      "</div>";
    $(".container").append(test);
    console.log(test);
    x += 4;
    sub++;
    err++;
  });
}
read();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

I am also implementing materialize.css in my project. However, I am encountering an issue where the submit function does not work as expected. It seems that the function executes but fails to verify whether the user has selected a radio button (possibly due to restrictions on jQuery methods). Placing the function inside $(document).ready() resolves this issue, but then the function itself stops working while other jQuery events within it function properly. This puzzling behavior has left me confused and seeking assistance. Any help would be greatly appreciated.

Answer №1

You may encounter an operator precedence issue here. In the expression "test" + check - 3, addition and subtraction are left associative. This means that it first performs "test" + check and then subtracts 3 from the result. However, trying to perform "test4" - 3 doesn't make sense because you can't subtract a number from a string. To fix this, use parentheses to override the default order of operations like so: "test" + (check - 3). This way, the subtraction is done first, and then the result is concatenated.

var obj = JSON.parse(
  '{"single": [{"id": 1,"question": "this is a question1?","option": ["option1","option2","option3","option4"]},{"id": 2,"question": "this is a question2?","option": ["option1","option2","option3","option4"]},{"id": 3,"question": "this is a question3?","option": ["option1","option2","option3","option4"]},{"id": 4,"question": "this is a question4?","option": ["optionu1","optionu2","optionu3","optionu4"]}],"multiple": [{"id": 1,"question": "this is a multiple question1?","option": ["optionm1","option2lj","option3","option4"]},{"id": 2,"question": "this is a multiple question...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

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

Having trouble with jQuery functionality when using Laravel 7 mix

Hey there! I'm currently using Laravel Mix to compile all my JS files, but I'm running into an issue with jQuery not working. I've tried adding the defer attribute, but no luck. Can anyone help me troubleshoot this? Thanks! Here's a sn ...

Send two field values via axios by utilizing a b-form-select component from the Bootstrap Vue library

I'm struggling to send two fields to my backend, but every time I attempt to do so, both values end up as null in the backend. I am uncertain about what mistake I might be making. <template> <div id="app"> <div> ...

If the request body exists, it should return a 409 error code

*Can anyone please help me with avoiding duplicate requests for existing names in NodeJS Express?* Here is my code: /* Post new person to persons */ app.post("/api/persons/", (req, res) => { const schema = { name: Joi.string().alphanum ...

Issue with Bootstrap 3 dropdown not receiving updates

My goal is to dynamically populate a bootstrap 3 dropdown menu from a MySQL database. Everything works perfectly the first time I load the data. However, when I add more rows to the database, they do not automatically show up in the dropdown. Only after ...

Discovering the Authentic Page upon Completion of Load using PhantomJS

I am facing an issue while automatically downloading a theme on Wordpress using PhantomJS. The problem arises because the page is not fully evaluated even after it appears to be done loading. When trying to interact with elements on the page, such as clic ...

The concept of Theme.breakpoints does not exist in MUI React, there is

I keep running into the same error where theme.breakpoints is undefined when I try to use theme.breakpoints.up in my code. The versions of the dependencies I am currently using are: "@emotion/react": "^11.9.0", "@emotion/styled&quo ...

The functionality to save user likes in React is not properly functioning on the like button

I created a like button in React that saves my choices, but it seems to be not saving the choices of other users. Additionally, it doesn't appear to restrict only authenticated users from marking likes. Can someone please help me identify what I' ...

Permanently removing artwork from the Canvas

I am facing an issue with my canvas drawing function. Whenever I clear the drawings on the background image by clicking a button, the old drawings reappear when I try to draw again. How can I permanently delete the cleared drawings so that I can start fr ...

Localhost Delay in XAMPP

As I work on developing my own website, I have opted to use XAMPP for hosting. After making modifications to the CSS, HTML files, and replacing the existing images with new ones in the designated folder, I encountered an issue. Despite restarting and re-i ...

Transforming an array of JSON objects into a Knockout observable array containing observable properties

My application utilizes an ajax call to fetch a JSON array. [ {"ID":2,"Name":"Name 1","CreatedOn":"/Date(1432892160000)/"}, {"ID":7,"Name":"Name 2","CreatedOn":"/Date(1432892160000)/"}, {"ID":8,"Name":"Name 3","CreatedOn":"/Date(1432892160000)/"}, {"ID":9 ...

RobotFramework encounters difficulty locating an element using JavaScript

After working with RF for the past few weeks, I came across a persistent issue that has been bothering me. I keep getting the following error: The element with the locator 'XXX' (just a template) cannot be found. Upon investigating the span tha ...

When using Sequelize, I encountered an error message from SQLite stating that the table does not exist despite having created

I am struggling to grasp the concept of how Sequelize operates and I can't figure out why I am encountering the SQLITE_ERROR: no such table: Users error even though I have created the table using sequelize.define. Here is my code: const { Sequelize, D ...

Save the selected value from the dropdown menu and automatically check the corresponding checkbox when it

I'm attempting to update the 'value' of a checkbox once an item is chosen from a dropdown list and then the checkbox itself is clicked. I have created a jQuery function that captures the value from the dropdown list (I omitted the code for t ...

Mastering all changes to the 'src' attribute in the DOM

I am currently coding in Javascript and trying to implement a feature that monitors new 'script' elements and blocks specific sources. I have experimented with using MutationObserver and __defineSetter__, both of which can monitor changes to the ...

A guide on designing a personalized search bar for MUI-Datatables with a sleek outlined style

Check out the default UI from MUI-Datatables v4.3.0 here: https://i.stack.imgur.com/rbHgD.png I want to create a style similar to this: https://i.stack.imgur.com/AUHqC.png Just so you know, I am using the following packages: "@mui/material": &q ...

The computer system encountered an issue in computing the values of the text

Possible Duplicate: Unable to get textfield value using jQuery My current project involves updating input fields based on user changes in quantity for items. Each item is retrieved from a database and I am generating invoices for customers. However, ...

Troubleshooting CSS problems with positioning 3 fluid div elements

I am in need of 3 dynamic div containers. container for main content image display container that changes size container on the side with changing width The issue I am facing is that the text needs to be below the image container which has a wider width ...

In JavaScript, the function is unable to access elements within an iteration of ng-repeat

I am using ng-repeat to display datepickers that are powered by flatpickr. To make this work, a script needs to be added on the page for each input element like so: <script> $('[name="DOB"]').flatpickr({ enableTime: false, dateForm ...

Incorrect measurement of text size

My attempt at creating a basic font size changer was working perfectly until I integrated it with the bootstrap framework. Strangely, when I try to increase the font size, it actually decreases instead. var baseFontSize; (function () { "use strict"; ...

Ways to verify the presence of an item in a MonoDB array

My MongoDB model looks like this: const userSchema = new Schema = ({ name: { type: String }, company: [ companyId: { type: String, }, movies: [ { genre: { type: String, enum: [ ...