Encountering a syntax error when attempting to generate a div dynamically with jQuery

I am in the process of creating a view application form using Bootstrap after submitting a form. Initially, I created it utilizing two 'div' elements. Now, I am exploring how to dynamically generate a div upon clicking a button:

<i> Section I: Insured Information</h4>
<div class="form-group dynamicDiv">
    <!--Wrap labels and form controls needed for optimum spacing !-->
    <div class="row top-buffer">
        <label class="col-md-5 labelAlignment">
        Name<span class="red">*</span></label>
        <div class="text-box-height col-md-7">
        <!-- Form controls automatically receive some global styling with              Bootstrap: !-->
             <input type="text" class="form-control" id="txtInsuredName"   placeholder="Enter Name"
              required oninvalid="setCustomValidity('Enter UserName')"      oninput="setCustomValidity('')" />
        <!-- To insert plain text next to label within a horizontal form, .form-control-static class is used  !-->
        <div class="col-md-10 form-control-static lblInsuredName">
        </div>
    </div>
</div>
<div class="row top-buffer">
    <label class="col-md-5 labelAlignment">
        Mailing Address Line 1<span class="red">*</span></label>
    <div class="text-box-height col-md-7 ">
        <input type="text" class="form-control" id="txtInsuredAddress1" placeholder="Enter Address"
            required oninvalid="setCustomValidity('Enter Mailing Address1')" oninput="setCustomValidity('')" />
        <div class="col-md-10 form-control-static lblInsuredAddress1">
        </div>
    </div>
    <footer>
        <div class="col-md-12" align="center">
            <div class="row top-buffer"> </div>
            <div class="row top-buffer"> </div>
            <button type="submit" class="btn btn-success" id="btnSubmit">
                Submit</button>
            <button type="submit"  class="btn btn-info"  id="btnView">
                ViewData</button>
            <input runat="server" type="hidden" id="hdnKey" value=""  />
            <div class="row top-buffer"> </div>
        </div>
    </footer>
<i>

I have stored the values in JSON format as a .json file and saved them into a hidden field. However, my challenge now is dynamically creating a second div for each textbox field in the form. Below is the jQuery function I attempted:

/*****************Function for showing view page using Query String******************/


$("#btnView").click(function() {
    var strUrlView = new String(window.location.href);
    strUrlView = strUrlView + "?key=" + $("#hdnKey").val();
    window.location.href = strUrlView;
});
var strUrl = new String(window.location.href);
if (strUrl.indexOf("key") != -1) {
    /*****************Hiding form-control div's ******************/
    //to decrypt the uniqueID
    var strKey = strUrl.split("key=")[1].replace("#", '');
    //Reading json and get data from json file to create the view
    var strFile = 'Data/JsonData/' + strKey + '.json';
    $.getJSON(strFile, function(data) {
        $.each(data, function(Key, Value) {
            //to convert control to span
            var ctrl = $("#" + Key);
            for (var k in Value) {
                //for replaceing textbox to label
                if (typeof Value[k] !== 'function') {
                    var strlblname = "div." + k.replace("txt", "lbl").replace("ddl", "lbl");
                    $(strlblname).text(Value[k]);
                }
            }
        });
    });
}
});

In an attempt to append dynamically, I wrote this line of code:

for (var k in Value) {
    $(".dynamicDiv").append(" <div class="form-group dynamicDiv"></div>")
    //for replaceing textbox to label
    if (typeof Value[k] !== 'function') {
        var strlblname = "div." + k.replace("txt", "lbl").replace("ddl", "lbl");
        $(strlblname).text(Value[k]);
    }
}

However, this resulted in a syntax error. Can someone help me identify my mistake?

Answer №1

$.each(data, function(Key, Value) {
            //changing control to span
            var ctrl = $("#" + Key);
            for (var k in Value) {
                $('.viewDiv' + j++).text(Value[k]);
            }
});

I eliminated the div with the 'form-static-control' class and included the 'viewDiv' class inside the div with the 'text-box-height' class.

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

Looking for solutions to manage mouseenter, mouseleave events and ensuring content dropdowns stay visible in Vue.js 2?

Hey there, I'm trying to figure out how to keep dropdown content from disappearing when using @mouseenter and @mouseleave. Here's what I have so far: <div class="wrapper"> <div class="link" @mouseenter="show = ...

The toLowerCase method seems to be malfunctioning along with several other functions

JS var score = 0 var yes = "yes" var pokemonName = []; var bg = []; var index = 0; document.getElementById('repete').style.visibility = 'hidden'; (function asyncLoop() { background = bg[num = Math.floor(Math.random() ...

JSON field with changing values

I'm currently working on structuring classes to fetch data from the following URL: Here is my current class setup: data class NearEarthObject (val asteroidObjects : Map<String, DateSelected>) data class DateSelected (val date: ArrayList<A ...

Struggling with parsing specific values in JSON file while trying to improve Python skills

Embarking on my first Python project focusing on Stardew Valley and its crop prices has been an exciting challenge. For those familiar with the game, you may know that each shop sells unique items, creating a diverse market. I am currently working with a ...

What is the problem with locating elements in Selenium with Java?

I've been encountering difficulties in finding elements on a webpage structured like this: <tr id="filter100" style="...." idx=0 <td> <div onclick=... style=... <table dir = "fil"> <tbody> ...

Using Selenium in Java to interact with popup elements

Attempting to retrieve and interact with pop-up/alert elements using selenium in Java has been a bit challenging for me. Below is the code snippet I have been working on: import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import ...

How can I achieve a similar functionality to array_unique() using jQuery?

When I select values from a dropdown, they are stored as an array like ["1","2","3"] Upon each change, the code below is executed to generate a new array based on the selected values: $('#event-courses-type').on('change', function(){ ...

Is utilizing React's useEffect hook along with creating your own asynchronous function to fetch data the best approach

After attempting to craft a function for retrieving data from the server, I successfully made it work. However, I am uncertain if this is the correct approach. I utilized a function component to fetch data, incorporating useState, useEffect, and Async/Awa ...

JavaScript code does not seem to be functioning properly on my computer, but it works perfectly fine on

While the code functions perfectly in JSFiddle, it seems to fail when I try to implement it in an HTML file. Despite my efforts, I am unable to pinpoint the source of the issue. If you'd like to view the working version, here is the Fiddle demo. Bel ...

Using Material UI with Reactjs for Background Image Mapping

I need some advice from everyone. I have an array of images and I've mapped the content, but for some reason I am unable to set a background image in the styles of a component. The other objects in the array are working as expected. {DlCards.map((mdlc ...

Issue with Gmail failing to render CSS in HTML email (svnspam)

After successfully setting up and configuring svnspam, I noticed that the emails sent to my Gmail account are missing the colored diffs. When examining the original email using Gmail's view original feature, I found the CSS code as follows: <html ...

jQuerry's on method fails to respond to newly added elements through the clone() function

I always thought that jquery's on() function would handle events for dynamically added elements in the DOM, such as those added via ajax or cloning. However, I'm finding that it only works for elements already attached to the dom at page load. Cl ...

AngularJS factory or filter failing to update properly

I have been working on a system that manages translations in my factory. I set the language as a string and then use a filter to update the view when the language changes. Everything works fine if I define the language in the view beforehand, but when I t ...

What are the steps to create an iOS app for reading articles that includes offline caching?

I am currently in the process of developing an application for reading articles. The data is being fetched from a server in JSON format and loaded into UITableView and UIWebView. Each article consists of images, videos, and text. I am aiming to implement o ...

Unable to Update the Status Code

When it comes to setting the status code to 9999, I am utilizing the basic Response.StatusCode. In this case, the page is accessed via an AJAX call and the status code is checked at readyState = 4. On detecting 9999 as the status code, an alert pops up wit ...

Creating a Duplicate of the Higher Lower Challenge Game

To enhance my comprehension of React, I am constructing a replica of the website: Instead of utilizing Google searches, I opted for a dataset containing Premier League stadiums and their capacities. Up to this point, I have crafted the subsequent script: ...

align-content and justify-content in flexbox are not producing the desired results

align-content and justify-content don't appear to be working when I test them in both Chrome and Firefox. I'm puzzled as to why they're not functioning as expected. #container { display: flex; flex-wrap: wrap; justify-content: cent ...

Resizing Div elements in React

I am currently working on a Drawer navigation feature and I am exploring the option of enabling mouse drag resize functionality. To achieve this, I have included a div element where I listen for the onMouseDown event. Once triggered, I then add an event li ...

What is the best way to position the top line next to the border?

I've been attempting to create a falling line effect on the left side of the box's border, but I can't seem to figure out what's causing the issue. Below is the code snippet: @import url('https://fonts.googleapis.com/css ...

Is there a way to retrieve a particular object from the state and access one of its elements?

I have a component called Tweets.js: import React, {Component} from "react"; export default class Tweets extends Component { constructor(props) { super(props); this.state = {tweets: [], users: []}; } componentDi ...