Exploring the process of linking multiple checkbox fields in a form with an ajax request

I have attempted the following method, but it is not working. I am able to retrieve the name from the form, but nothing gets assigned to the "sharewith" variable. My goal is to assign all selected checkboxes to one id called "sharewith" and then send them to the server using an AJAX request. Is this possible?

Form:

 <div class="modal-body">
            <p class="statusMsg"></p>
            <form role="form">{% csrf_token %}
                <div class="form-group">
                    <label for="inputName">kcategory</label>
                    <input type="number" class="form-control" id="inputName" placeholder=node name/>
                </div>
                <div class="form-check" id="sharewith">
                    <label for="sharewith">Share with</label></br>
                 {% for sharewith in users %}
                   <input class="form-check-input position-static" type="checkbox"  value="{{ sharewith.uid }}">
                     <label>{{ sharewith.umail }}</label></br>
                  {% endfor%}
                </div>
            </form>
        </div>

AJAX:

function submitContactForm() {
   var token = '{{csrf_token}}';
   var name = $('#inputName').val();
var sharewith = $("#sharewith").val()
if (name.trim() == '') {
    alert('Please enter your name.');
    $('#inputName').focus();
    return false;
}else{
    $.ajax({
        headers: { "X-CSRFToken": token },
        type:'POST',
        url:'sharing',
        dataType:"json",
        traditional: true,
        data:'contactFrmSubmit=1&name='+name+'&sharewith'+sharewith,
        beforeSend: function () {
            $('.submitBtn').attr("disabled","disabled");
            $('.modal-body').css('opacity', '.5');
        },
        success:function(msg) {
            if (msg == 'ok') {
                $('#inputName').val('');
                $('.statusMsg').html('<span style="color:green;">Successfully saved</p>');
            } else {
                $('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
            }
            $('.submitBtn').removeAttr("disabled");
            $('.modal-body').css('opacity', '');
        }

    });
}

}

How can I assign all checkboxes to "sharewith"? Any assistance would be greatly appreciated.

Answer №1

include both name and id in the input class for checkbox fields within the Template

<input class="form-check-input position-static" name="mycheckboxes" id="myCheckboxes" type="checkbox"  value="{{ sharewith.id }}">

utilize ajax and JavaScript:

function SubmitContactForm() {

    var token = '{{csrf_token}}';
    var name = document.getElementById("inputName").placeholder;

    var sharewith = getChecked();
    function getChecked(){
        var inputs = document.getElementsByName('mycheckboxes');
        var key_values = [];
      for(i=0; i<inputs.length; i++) {
         input = inputs[i];
      if (input.type=='checkbox' && input.checked) {
        key_values.push(
            encodeURIComponent(input.name) +
            "=" +
            encodeURIComponent(input.value)
        );
    }
}
var form_encoded_data = key_values.join("&");
return form_encoded_data;
};


    if (name.trim() == '') {
        alert('please choose a node to share.');
        $('#inputName').focus();
        return false;
    } else {
        $.ajax({
            headers: {"X-CSRFToken": token},
            type: 'POST',
            url: 'sharing',
            dataType: "json",
            traditional: true,
            data: 'name='+ name+"&"+sharewith ,
            beforeSend: function () {
                $('.submitBtn').attr("disabled", "disabled");
                $('.modal-body').css('opacity', '.5');
            },
            success: function (msg) {
                ##copy and paste
                }
                $('.submitBtn').removeAttr("disabled");
                $('.modal-body').css('opacity', '');
            }
        });
    }
}

views.py:

now you can easily access checkboxes by using getlist("checkboxes")

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 command is failing to include functionality with the yarg npm package

I have been attempting to incorporate a command using yargs, however, after executing my code, the command does not seem to be added successfully. Below is the snippet of what I am attempting: const yargs = require('yargs') //create add command ...

Choose a radio button from a React Native FlatList

I am new to React Native and I'm working with the expo-radio-button component. However, I'm facing an issue where I can't seem to select only one radio button at a time in a flatlist. When I try to select a single button, it ends up select ...

Issue: Unable to access 'filter' property of null object

I've been working on a small react dropdown task and it's running smoothly in Google Chrome. However, I encountered an error when testing it on MS Explorer. Even after deploying it on a live server, the issue persisted. The specific error message ...

How can I use jQuery to separate special characters from letters in a string?

I'm facing an issue with my code related to validation. There is a existing validation in place that restricts users from entering letters and special characters in a textfield. Now, I need to incorporate this validation into my code but I'm uns ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...

Discover the method for invoking a Javascript function within a Leaflet popup using HTML

Upon clicking on a marker on the leaflet map, I aim to trigger a popup box that contains five elements: Title Description Image Button (Next Image) Button (Previous Image) To achieve this, I attempted to include a custom popup for each feature ...

The delete_node() function in jstree does not seem to be removing nodes

In my attempt to create a custom context menu for different nodes, I've managed to display different labels for clicks on folders or files. However, I am facing some challenges when trying to delete them. Take a look at my code snippet. Due to diffic ...

Attempting to eliminate redundant data retrieved from an XML file being presented on my webpage

I need help deleting duplicate artists that appear when retrieving information from an XML file using JQuery. How can I achieve this? Check out the JS file below: $(function(){ $(window).load(function(){ $.ajax({ url: 'http://imagination ...

Tips for updating a section of a webpage without the need to redirect to a different page: use technologies such as Express, Nodejs, and M

In the midst of developing a two-player game where one player must guess a word within 10 tries, I find myself facing a challenge. I need to display the player's guesses and scores in a table without refreshing the entire page. Unfortunately, my exper ...

Node.js with Koa: Discontinuation of generator usage on the next step

I am working with a custom object in which I pass a parameter, and then I need to search for all documents in my collection and process them. Here is the code for my custom object: var db = require('../lib/db'); function Widget(n,l,c,o,t,p) { ...

The setState function in React Native seems to be having trouble updating

I've been attempting to access state from a component, but for some reason, I'm not seeing any changes when I use setState(). Here is the current state of my component: class MyTestComponent extends React.Component { constructor(props){ ...

When the user clicks, I plan to switch the audio source

I am looking to update the audio source when a button is clicked, but I am having trouble getting it to work. image description data() { return { audioSrc: '' } }, methods: { setActiveAudio(item) { this.$refs.audioE ...

Adding a property conditionally in jsx: A guide

I have a simple example of Material UI RadioGroup code that I want to display conditionally in either a row or column format. By default, it is displayed in column format. Below is the code snippet: <RadioGroup aria-label="gender" name=&q ...

Fixing a div at the top post scroll - bug on iOS mobile device

I am looking to achieve a similar effect as demonstrated in the example below: https://css-tricks.com/scroll-fix-content/ Essentially, the goal is to have a div become fixed at the top of the page after scrolling to a certain point. Initially, the div wil ...

Is it possible to utilize the default error handling page rather than a specific view for expressing

Currently, I'm going through a tutorial on MDN Express for building a "Local Library" application that utilizes Pug (Jade) as its templating engine. In this segment of the tutorial, it explains the process of creating a controller to manage a form POS ...

Can Jquery use .hover to add a class or Child:hover to impact its parent element?

I have been searching for a solution tailored to my specific needs, and I am encountering difficulties in getting a seemingly simple jQuery code to function as expected. Here is the link to my basic fiddle: http://jsfiddle.net/LBHxc/ (I apologize for the ...

Enabling Multiple Login Feature in Node.js

const handleLogin = async (req, res) => { const User = require("../models/user"); const LoginInfo = require('../models/login_info'); try { const { email, mobile, password, otp } = req.body; const params = []; if(ema ...

Arrange and display similar objects together

I have a list of items in a listView that need to be visually grouped based on their class, displayed within boxes. For example, I have 5 items with the following classes: <div class="1"></div> <div class="1"></div> <div class= ...

Elements that are hidden or not displayed are still able to receive mouse over events

I am in the process of learning how to handle events within svgs and I have encountered a strange issue. Currently, I am working on an infovis project where I create an interface to display various column-graphs. This part is functioning well so far. Ho ...

Implementing ActiveTabChanged in an Ajax tabContainer

Can someone help me figure out how to create ActiveTabChanged for an Ajax tabContainer? I tried double clicking on the tabContainer but nothing happened. If it was a Button, I know you can just double click to generate the code below. If you have experien ...