Click on the checkbox to send a value via ajax in an MVC framework

I've recently created a data table that includes a checkbox in each row and a dropdown menu in one of the columns. Everything seems to be working fine so far, with a single submit button at the top for user input. The main goal here is to allow users to select checkboxes and dropdown options within rows, and then update the selected rows once submitted.

Here's a snippet of my current code in the View:

<input type="button" id="delete" value="Submit" />
<table id="example" cellpadding="10" width="100%>
        <thead>
            <tr>
                <th><input id="checkAll" type="checkbox" /></th>
                <th style="text-align: center; border: 1px solid #eaeaea">Email Address</th>
                <th style="text-align: center; border: 1px solid #eaeaea">Select Option</th>
        </tr>
        </thead>
        <tbody>
            @foreach (var row in Model)
            {
             <tr>
            <th scope="row"><input type="checkbox" class="checkBox" value="@row.site"></th>

         <td class="gfgusername" style="width: 20%; padding: 0px; text-align: center; border-left: 1px solid #eaeaea; border-right: 1px solid #eaeaea">
        @row.EmailAddress.Trim()
    </td>
     <td style="width: 20%; padding: 0px; text-align: center; border-right: 1px solid #eaeaea">
        <select class="priorityList" name="priorityList2"><option>Yes</option> 
        <option>No</option><option>Delete Folder</option></select>
      </td>
       </tr>            }

        </tbody>
    </table>

  <script language="javascript">
  $(document).ready(function () {
   $("#delete").click(function () {
            $('input:checkbox.checkBox').each(function () {
                if ($(this).prop('checked')) {

                  ???????????

                });
            

            var options = {};
            options.url = "/Dashboard/Delete";
            options.type = "POST";
            options.data = ????;
            options.contentType = "application/json";
            options.dataType = "json";
            options.success = function (msg) {
                alert(msg);
            };
            options.error = function () {
                alert("Error while deleting the records!");
            };
            $.ajax(options);

        });

    });
  </script>

My current question revolves around the concept of saving user responses and passing them through AJAX calls. While I understand how to pass a single value when a user wants to delete something, I'm unsure about how to pass multiple values through ajax, specifically those associated with user-selected checkboxes.

Answer №1

Here is the structure of your Delete function:

$(document).ready(function () {
    $("#delete").click(function () {
            var checkboxesArray = [];
            $('input:checkbox.checkBox').each(function () {
                if ($(this).prop('checked')) {
                    checkboxesArray.push($(this).attr("value"));
                }
            });
            var selectedValue= $('#priorityList2').find(":selected").text();
            var jsonData = {
               myCheckboxes : checkboxesArray,
               mySelectedValue: selectedValue
            };

            var options = {};
            options.url = "@Url.Action("Delete", "Dashboard")";
            options.type = "POST";
            options.data = {"json": JSON.stringify(jsonData)};
            options.dataType = "json";
            options.success = function (msg) {
                alert(msg);
            };
            options.error = function () {
                alert("Error occurred while deleting the records!");
            };
            $.ajax(options);
    })
});

Your Controller method should be like this:

using System.Web.Script.Serialization;

[HttpPost]
public JsonResult Delete(string json)
{
  var serializer = new JavaScriptSerializer();
  dynamic jsonData = serializer.Deserialize(json, typeof(object));

  //Extract necessary data from AJAX call
  var checkboxValues = jsonData["myCheckboxes"];
  var mySelVal = jsonData["mySelectedValue"];
  //Perform required operations
}

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

Problem with using React state hook

Trying to implement the state hook for material-ui's onChange feature to manage error texts, I encountered an issue. I have included a screenshot of the error displayed in the console. https://i.sstatic.net/qjed8.png Below is the snippet of my code: ...

Sorting arrays in JavaScript can become tricky when dealing with arrays that contain values from two different arrays

When working with two arrays in JavaScript that are received from PHP, I combine them into a single array. Each element in these arrays contains a created_at value (from Laravel), and I want to sort these elements by their created_at values. The issue ari ...

What is the process for determining the directory in which CKEditor looks for configuration and language files?

When CKEditor is loaded on a page, it searches for its configuration files relative to the location where it was initially loaded from, rather than the location of ckeditor.js. For example, loading CKEditor on the page http://www.example.com/articles/1 wou ...

Error: Unable to retrieve the "error" property as the data is not defined

Encountered a title error and struggling to fix it :(. Attempting to retrieve data from a signup page, here is the snippet of my JavaScript code: const SignupComponent = () => { const [values, setValues] = useState({ name: 'ryan', emai ...

Guide on implementing automatic callbacks with AJAX

I am facing an issue with my index page that has one input tag and one division. There is an ajax function that retrieves data from the server, but I am encountering a problem. When I enter a single letter, it returns 3 records. Then, if I add another lett ...

Is there a way to implement seamless scrolling within an absolute element using Jquery?

Hey there! I recently implemented smooth scrolling on my website, but it seems to only work on single-page layouts. How can I make it function properly within an absolutely positioned scrollable element? Here are the link to my website and the correspond ...

Refreshing a Next.js page results in a 404 error

I've set up a Next.js page called page.js that can be accessed through the URL http://localhost:3000/page. However, I have a need to access this page through a different URL, namely http://localhost:3000/my-page. To achieve this, I decided to utilize ...

Master the art of horizontal scrolling in React-Chartsjs-2

I recently created a bar chart using react.js and I need to find a way to enable horizontal scrolling on the x-axis as the number of values increases. The chart below displays daily search values inputted by users. With over 100 days worth of data already, ...

Displaying the appropriate DIV element based on the value entered by the user

I am encountering some difficulties... I have an <input> field. Depending on the input, one of the various <div> elements should be displayed. For now, it's just a text (e.g. "Your plan contains less than 1500 kcal!"), but later, the div ...

Is it possible to trigger an event for only one connected client instead of broadcasting it to all clients using socket.io?

I am seeking a way to send an event to just one connected client, rather than broadcasting it to all clients using io.emit(). ...

Utilize the power of PIXI.js to effortlessly convert your canvas into a high-quality image without encountering

I'm currently working on exporting the entire canvas as a PNG using PIXI.js within a React app that incorporates react-pixi. My version is 6.5 and I've been trying out the following code: // MyComponent.tsx <button onClick={exportImage} /> ...

How can I remove the most recently added div using JavaScript?

Currently, I am expanding my knowledge in Javascript and encountered a problem. There is a function set up to add boxes every time I click "Add Data". I can continue adding multiple boxes this way, but I need assistance with implementing a button labeled " ...

Event handler does not handle exceptions thrown from Express routes

I recently created an Express route to test my event handler for uncaught exceptions, but I'm facing an issue where the event handler is not being triggered when an error is thrown from the route code: app.js: process.on('uncaughtException&apos ...

Effortlessly upload multiple files in PHP using AJAX and enable automatic uploading upon selection

I am currently working on developing an upload form for audio files similar to websites like SoundCloud and Hulkshare. The process goes as follows: Click the upload button. Select multiple files. Upon pressing ENTER or OPEN (on Windows), the files will ...

Find the average value of an array containing objects

Imagine I have an array of objects like this: const BookDetails = [ { bookName: 'Harry Pottar', readingTime: 10663 }, { bookName: 'Harry Pottar', readingTime: 10986 }, { bookName: 'kaptura Tech', readingTime: 7034 } ] I ...

Learn how to successfully place a draggable object into a sortable container while ensuring that the dropped item is a personalized helper element rather than the original object

The jQuery draggable/sortable demo showcases the process of dropping a clone of the draggable item (both draggable and sortable elements share the same structure). However, I am interested in dropping a different DOM structure. For example, when dragging a ...

No closing bracket was found as the NodeJS & Jade string reached its conclusion

Embarking on my journey into the world of node.js (following the steps in the rolling with mongo tutorial), I have created a jade file which looks like this: extends layout block content h1= title form(method="post") div div span Tit ...

I am struggling to set a required input in Angular2

I am new to Angular and currently working on a project that requires input validation to ensure that no field is left blank. The project consists of an HTML file along with a .ts file for functionality. Below is a snippet from the HTML: <div class="f ...

Issue with multiple sliders on the page not initializing pagination upon refreshing the page using Slick library

Every time I refresh the page, the pagination value fails to initialize until I click on either the next or previous button. var $slickElement = $('.paragraph-slider, .gallery-slider'); $slickElement.each(function() { if($(this).find('. ...

Filtering an object using data in AngularJS

My current data object structure looks like this : $scope.data = [ { "name": "1001", "queue": [ { "number": "111", } ] }, { "name": "1002", "queue": [ ] ...