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

Accessing an object from an AngularJS controller in an external function

I previously inquired about this issue and received a suggestion to add a service, but it did not solve the problem. I am trying to access a variable from a controller ($scope) within an external function. Below is a snippet of the example: app.controll ...

Is it possible for me to overlap a text over hidden text, and if the hidden text becomes visible through JavaScript, my text will shift to the right of the now visible hidden text?

I'm currently working on a website for a company that requires users to complete all the information before proceeding. To achieve this, I created a form with the following code: <form action="Owners Infoback.php" onsubmit="return validateFo ...

The Magnificent jQuery Widget Factory's _trigger Instance

When utilizing the _trigger function to initiate events, I often come across a recurring issue that I struggle to fully comprehend. The problem arises when there are multiple instances of my widget on the same page. In such cases, the most recently instan ...

The jQuery dropdown menu smoothly expands to reveal all hidden submenu options

I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 7 ...

What is the best way to organize data subsets in Firebase?

I am currently working on saving data from multiple sections within my webapp. One section involves storing employee information, while the other deals with employer group information. However, when I save this data in Firebase, it all gets organized by ID ...

An issue occurred during the hydration process, causing the entire root to switch to client rendering since the error occurred outside of a Suspense boundary

I've started seeing some errors and warnings: Error: An error occurred while hydrating. Since it happened outside of a Suspense boundary, the entire root will switch to client rendering. Error: Hydration failed due to initial UI not matching what was ...

The successful loading of tab favicons in the DOM of an angular chrome extension is a triumph, however, explicit XHR requests are unfortunately

I've been immersed in developing a Chrome extension with Angular 5. Successfully, I managed to extract favIconUrls from the tabs API and link them to my popup.html's DOM. The icons are retrieved and displayed without any hiccups. See an example ...

Unable to transmit data to CodeIgniter controller through ajax communication

I'm struggling with sending a value from an input element to a Codeigniter controller using ajax. The problem arises because I am using a WYSIWYG editor (summernote), which only allows me to receive the input inside a <script>. However, when I ...

Enable or disable dropdown based on selected radio button status

I need the dropdown to be disabled unless the radio button labeled prov is selected. It should only be enabled when prov is chosen. I attempted to create a demo, but it's not functioning correctly and I can't figure out why. HTML: <td colsp ...

What is the best way to make a Modal triggered by a loop embedded within a table function properly on mobile devices?

While the modal is functioning properly on desktop, it seems to be encountering issues on mobile devices. The modal appears behind the background and is confined by the boundaries of the table (tbody). Below is the code snippet for triggering the modal: ...

Node.js is throwing GitHub API 401 Bad Credentials error, whereas curl is not encountering the

I am attempting to authenticate on Enterprise GitHub using @octokit/rest. When I execute the following Curl command, I receive a list of API URLs: curl -u "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80edf9c0e5ede1e9ecaee3e ...

Upon calling the createModalAddPost() function, a single window is triggered to open

Hey there, I'm having a JavaScript question. So, I have a panel that opens a window, and it works fine. But the issue arises when I close the window and try to open it again - it doesn't work. I have to reload the page every time in order to open ...

How can I incorporate a custom color into a preset navbar on an HTML webpage?

<div class="navbar-header"> <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" style="color: blue;" class="navbar-toggle collapsed" type="button"> <i class="fa fa-reo ...

Real-time PHP Algorithm Reports using Ajax

If the following code is contained in a file called test.php: for ($i = 0; $i < 1000; ++$i) { //Operations... ALERT_TO_MAIN_PAGE($i); } How can I use AJAX to call test.php from main.html and track the progress of $i with live values? As eac ...

Perform a search within an iframe

Despite the fact that iframes are considered outdated, I am attempting to create a browser within an HTML browser. I have implemented a search bar that opens the typed input in a new window which searches Google. However, I would like to modify it so that ...

By using Yii2, you can pass an id to the URL by simply clicking on a

I am struggling with sending the post_id from a div containing text content (retrieved from a database) to a URL in order to render a view page displaying the entire content. I am using Yii2 and believe I need to use JavaScript for this task, but I am unsu ...

Can you provide me with some insight on the process of iterating through an object utilizing the

I've developed an app that randomly plays a sound from a selected array when a button is pressed. Now, I want to add the functionality to display and play all sounds in the array upon request. I've explored various methods such as for loops and ...

Apply a specific CSS class to a division depending on the currently active cookie

I have implemented cookies on specific pages using https://github.com/carhartl/jquery-cookie. Could someone guide me on how to apply a CSS class to an ID (e.g., adding class .red to #mouse if the cookie named "socks" is active)? For example: If there is ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

Storing data in real time

I am working on creating a website where users can customize their navigation menu by selecting list items. My idea is to save the selected menu items in a cookie so that users do not have to register on the website. Is it possible to store real-time dat ...