Build a JSON object using form data

Check out my form at this link: http://jsfiddle.net/sxGtM/4743/. Upon submitting the form, I need to generate a JSON object with the following structure:

data = {
        'voted_questions': [question.pk, question.pk, question.pk, question.pk],
        'answers': [
        {
        'question': question.pk,
        'option': option.pk,
        },
        {
        'question': question.pk,
        'option': option.pk,
        },
        ]
    }

The values of question.pk and option.pk are numerical identifiers for each question and option (essentially their IDs). Can anyone provide guidance on how to create this JSON format?

Answer №1

It seems a bit redundant to ask for a list of answered questions when you already have a list of answers that includes the question IDs. Nevertheless, here is what you requested.

HTML

<h2>Form</h2>
<form action="" method="post">
Which country is known as the Land of the Rising Sun?<br/>
<input type="hidden" name="first" value="1"/>
Japan:<input type="radio" name="first" data-questionid="1" value="11"/><br/>
China:<input type="radio" name="first" data-questionid="1" value="12"/><br/>
Which city is known as The Big Apple?<br/>
<input type="hidden" name="second" value="2"/>
New York:<input type="radio" name="second" data-questionid="2" value="13"/><br/>
Los Angeles:<input type="radio" name="second" data-questionid="2" value="14"/><br/>
<p><input type="submit" /></p>
</form>
<h2>JSON</h2>
<pre id="result">
</pre>

Javascript

$(function() {
    $('form').submit(function() {
        var voted_questions = [];
        var answers = [];

        $('input[type="radio"]:checked').each(function(){
            voted_questions.push($(this).data('questionid'));
            answers.push({'question':$(this).data('questionid'), 'options':this.value});
        });

        var data = {
            'voted_questions': voted_questions,
            'answers': answers
        };

        $('#result').text(JSON.stringify(data));
        return false;
    });


});

jsfiddle

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

The messageReactionAdd event has suddenly stopped functioning without any explanation

Currently, I am developing a Discord bot that assigns the role "Voteur" to a user when they react to an embed message created by the bot. Everything was functioning perfectly until recently, but for some reason, it has stopped working. The bot successfull ...

Displaying XML data in an HTML table

Encountered a challenge while fetching data from an external XML document using JS. Following the w3schools tutorial for AJAX XML, but faced an issue I couldn't resolve. The XML structure is as follows: <root> <document-id> <author ...

How can I manipulate the JSON property, an array of objects, within a React component?

As a newcomer to react development, I am facing an issue while trying to display a product page with its summary using JSON data containing arrays of objects. Upon attempting to use .map function, I encountered an error stating that the prop is undefined. ...

Clicking on a specific month results in displaying only one row from the database rather than showing all rows associated with that particular month

I am facing an issue with my calendar feature on the website. The problem is that when I click on a specific month, it should display all the data associated with that particular month. However, the current code does not seem to work as expected. For insta ...

What is the best way to convert the key, value pairs from a JSON column in a dataframe into individual columns for keys and their corresponding values in Python?

I am currently working with a data frame that contains JSON format data in a column called cast. My goal is to unpack the key and value of each row in the cast column into separate columns in the data frame, where each key corresponds to a new column and i ...

Sending complete form details to a service using Angular

Is there a way to post all form fields without having to individually specify each one? I have a form with numerous fields and I would like to send the entire form object in one go using a post method. However, when I attempt to do this by posting the $sco ...

What are some strategies to enhance the efficiency of this code and reduce repetition?

Here's an overview of the component in question export default () => { const { currentUser, logout } = useAuth(); const [sideBarOpen, setSideBarOpen] = useState(false); const theme = useTheme(); const classes = useStyles(); const isSmall ...

Complex Notepad++ duplication, substitution, and addition operations

I have a collection of random strings listed on individual lines in my Notepad++. 127.0.0.1 badwebsite.com dontgohere.com Is there a way to transform them into the following format using Notepad++? {"blocked":true,"flagged":true,"string":"127.0.0.1","ja ...

Placing jQuery scripts in Blogger platform: A guide

After finding the correct codes to solve my problem in previous questions, such as How do I get an image to fade in and out on a scroll using jQuery?, I came across this helpful code snippet: var divs = $('.banner'); $(window).scroll(function(){ ...

What is the purpose of incorporating the replace function in my regular expression for Palindromes?

I'm currently tackling some challenges on FreeCodeCamp and I've hit a roadblock in a simple task which requires checking for palindromes. The solution provided involves the following step: str = str.replace(/[^a-zA-Z]/g, '').toLowerCas ...

Having trouble getting the reset select function to work

I'm in the process of developing a website where I'm facing an issue with resetting my form that is constructed using jQuery Uniform. Despite my efforts, I am unable to successfully reset it. Below is the header code snippet: $j(function() { ...

The servlet is successfully receiving a JSON post, but unfortunately, it is not being displayed

Currently, my focus is on JAVA programming. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("TEST TOMCAT SERVLET"); S ...

What is the process for swapping out a file input tag with a specific file already chosen?

As I attempt to process a file one line at a time, I came across this helpful solution. Unfortunately, the method involves using a file input tag to choose a file for reading. I am in search of a way to bypass the file input tag and specify a file in advan ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Google Feed API - Retrieving saved data from RSS feed cache

We have implemented the Google Feed API to display our latest blog posts on our website. However, even after 24 hours, our most recent post is still not appearing on our site. Despite confirming that the RSS feed contains the newest content, it seems that ...

My goal is to assign unique class names to each button in a list located inside a drawer, allowing them to be called individually when needed

return ( <Box sx={{ display: "flex", justifyContent: "space-between", width: "100%", height: "100%", overflow: &q ...

Directive containing tracking code script

I'm working on creating a directive to dynamically include tracking code scripts in my main page: <trackingcode trackingcodevalue="{{padCtrl.trackingnumber}}"></trackingcode> This is the directive I have set up: (function () { 'use ...

java printwriter not cooperating with javascript

Hey there, I'm currently working on a webpage created from a servlet using PrintWriter. I'm adding HTML, CSS, and JavaScript to the page, but unfortunately, the JavaScript functions are not functioning properly. Could this be due to a syntax erro ...

Modifying button text with jQuery is not feasible

I'm facing a challenge with jQuery and I need the help of experienced wizards. I have a Squarespace page here: . However, changing the innerHTML of a button using jQuery seems to be escaping my grasp. My goal is to change the text in the "Add to car ...

Refreshing the previous tab upon changing tabs in React Navigation TabNavigator

I am currently working with a route structure that looks like this: StackNavigator -StackNavigator -TabNavigator --Tab1 ---Route 1 (Stack) (initial) ---Route 2 (Stack) --Tab2 ---Route 3 (Stack) (initial) ---Route 4 (Stack) The issue I am facing is that ...