What is the process for sending the selected checkbox text to an action result on a Razor page?

Working with asp.net core razor pages, I am passing the selected id as an array successfully.

However, the issue arises when the selected text value for the checkbox is not being passed or displayed.

The problem seems to be occurring on this line of code:

selectedClassText.push($(this).next('label').text());

Upon debugging the action result with string[] classidsText, it displays null.

I specifically need to pass the selected text alongside the checkbox as an array.

In the razor page .cs file that retrieves the class id text:

public JsonResult OnGetSubAccountClassName(string[] classIds, string[] classidsText)
{
    var assetsSubAccountName = _IAssetsService.GetJdeAssetSubAccountClassName(classIds);
    AssetCountGeneration.JDEAssetSubAccountClassNameDetails = assetsSubAccountName;
    return new JsonResult(assetsSubAccountName);
}

From jQuery AJAX in the page's cshtml file, I send the selected displayed text using selectedClassText.

$(document).on('change', '.classCheckbox', function () {
      var selectedClassIds = [];
      var selectedClassText = [];
$('.classCheckbox:checked').each(function () {
    selectedClassIds.push($(this).val());
    selectedClassText.push($(this).next('label').text());
});
      console.log("selected items" + selectedClassIds)
      if (selectedClassIds.length > 0) {
          $.ajax({
              url: '?handler=SubAccountClassName',
              type: 'GET',
              traditional: true,
              data: { classIds: selectedClassIds, classidsText: selectedClassText },
              success: function (response) {
                  $('#subClassesList').empty();
                  $('#subClassesContainer').show();
                 
                  var subClassesContainer = $('<div data-class-id="' + selectedClassIds + '"></div>');
                  $.each(response, function (i, item) {
                      $(subClassesContainer).append('<input type="checkbox" class="subclassCheckbox" name="selectedSubClasses" value="' + item.subClassAccountId + '" /> ' + item.subClassAccountName + '<br />');
                  });
                  $('#subClassesList').append(subClassesContainer);
              }
          });

Update:

I attempted the code below but it didn't work, how can I resolve this issue?

When creating the checkbox list before triggering the change event, I have created it as follows:

$('#btnDisplay').click(function (event) {
      event.preventDefault();
      var dropdown = $('#accountclassname-select');
      dropdown.empty();
    
      $.ajax({
          url: '?handler=AccountClassName',
          type: "GET",
          dataType: "json",
          success: function (response) {
              $('#classesContainer').show();
              $('#classesList').html(''); // Clear existing classes
              $('#classesList').append('<input type="checkbox" class="classCheckbox" value="0" /> All <br />');
              $.each(response, function (i, classes) {
                  $('#classesList').append('<input type="checkbox" class="classCheckbox" value="' + classes.classAccountId + '" /> ' + classes.classAccountName + '<br />');
              });
             
          }
      });
  }); 

Important Notes:

I do not have a label to append the text to,

I have created the list as shown below:

$(subClassesContainer).append('<input type="checkbox" class="subclassCheckbox" name="selectedSubClasses" value="' + item.subClassAccountId + '" /> ' + item.subClassAccountName + '<br />');
                      });

Answer №1

Here's a Suggestion

If you want to include label text as custom attributes in an input field, consider the following example:

<input type="checkbox" class="classCheckbox" value="' + classes.classAccountId + '" data-label="'+ classes.classAccountName +'"/> ' + classes.classAccountName + '<br />

Then, within your loop, you can access and store the custom attribute (label text) like this:

var selectedText = $(this).attr("data-label");
selectedClassText.push(selectedText);

Answer №2

Important notes

I am unable to attach a label to the text being appended.

$(subClassesContainer).append('<input type="checkbox" class="subclassCheckbox" name="selectedSubClasses" value="' + item.subClassAccountId + '" /> ' + item.subClassAccountName + '<br />');

If you want to push item.subClassAccountName into selectedClassText when its checkbox is selected, consider placing it within a <label>:

$(subClassesContainer).append('<input type="checkbox" class="subclassCheckbox" name="selectedSubClasses" value="' + item.subClassAccountId + '" /> <label>' + item.subClassAccountName + '</label><br />');

This code requires the element immediately following the checkbox to be a label in order to work properly.

selectedClassText.push($(this).next('label').text());

If anything is placed between the checkbox and the label, this code will no longer function correctly.

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

Distinct vertical menus with varying widths but sharing the same CSS code for the submenus

How can I create a vertical menu bar with submenus on the right side? The first submenu appears correctly, but the second one is narrower than the first. It seems like they have the same code, yet they look different. Below is the HTML code: <div clas ...

What is the best way to resize an image within an SVG shape to completely fill the boundaries?

There is an SVG shape in the form of a parallelogram that has been filled with an image. To view the demo, click here. The code for the SVG object is as follows: <svg style="overflow:visible; margin-left:111px; margin-top:22px; " height="86" width=" ...

What is the best way to insert a new row into a table upon clicking a button with Javascript?

Hi everyone, I'm facing an issue with my code. Whenever I click on "Add Product", I want a new row with the same fields to be added. However, it's not working as expected when I run the code. Below is the HTML: <table class="table" id="conci ...

contrasting the application of logic in Rails controllers versus JavaScript within the .js.erb files

When dealing with a large "data" active record object that needs to be filtered based on user interactions on a page, the question arises about where to place the data-filtering logic. Currently, the filtering is done in the rails controller action, simpli ...

personalizing jquery templates

Currently, I am utilizing a jQuery template to showcase specific values. Within this template, I have included an if statement to determine if the age is considered old or not, with the result altering the background color accordingly. Previously, the co ...

Adjust the height and eliminate gaps between rotated divisions

I'm currently working on a floating menu that includes several links. I've successfully applied a CSS style to rotate the menu vertically (-90deg), but I'm facing an issue with the height being greater than desired. How can I reduce the heig ...

Preventing the setting of the returnUrl parameter by a partial view's Ajax ActionLink in ASP.NET MVC 2

When working with a master/detail scenario, it's common to use an Edit ActionLink that retrieves the partial details view using a jQuery Ajax call; isn't that typical? However, I've encountered an issue when a user's authorization toke ...

What is the best way to showcase all menu and submenu items in separate dropdown lists?

Having trouble with my code, it's not functioning properly. I can't pinpoint the error. The menu displays correctly but the submenu isn't showing up under specific menus. Here is the code snippet: ##Table: menus## id name ...

Utilizing Jquery Ajax to Access WCF Service

I have been struggling to create a WCF service and make AJAX calls to its methods using jQuery. Despite reading solutions on Stack Overflow, I am still unable to resolve the issue. Any assistance would be greatly appreciated. The code snippet I have is as ...

Learn the process of transferring information through ajax while managing dependent drop-down menus

I have successfully set the initial value from the first combo-box and now I am looking to send the second variable from the second combo-box and receive it in the same PHP file. Below is the Ajax code snippet: $(document).ready(function(){ $(".rutas") ...

Performing calculations with jQuery to extract the value of a selected dropdown option and a text

I am attempting to calculate the total amount by multiplying the value entered in a text box labeled qty1 by the price retrieved from a select box using ajax. <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ ...

Ways to disable mousewheel function in jQuery

I am trying to deactivate the mouse scroll in jQuery and successfully did so, however, I encountered this error message jquery.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See Thi ...

Retrieving JSON Data from an API with JavaScript/jQuery

Having some trouble with JSON parsing using jQuery and JavaScript. I'm trying to fetch weather information from the open weather simplest API, but for some reason it's not working. When I hardcode the JSON data into a file or my script, everythin ...

Dealing with JSON Stringify and parsing errors in AJAX

I've been troubleshooting this issue for hours, trying various suggestions found online, but I'm still encountering a problem. Whenever I encode function parameters using JSON.stringify and send them to my PHP handler through AJAX, I receive a pa ...

extracting data from selected checkboxes using ajax

I am having an issue trying to retrieve the values of the checked checkboxes here. The problem arises because it returns as an array and ends up being undefined. Can someone please assist me with a solution? Thank you. <form> <input type="check ...

Is there a way to modify the Javascript for this Contact Form to trigger a different action if a specific key is pressed instead?

I have been working on a Contact Form that integrates Google Scripts. Everything seems to be functioning well as it successfully sends emails and formats them properly in my inbox. However, there are two issues that I am encountering: -I want to exclude t ...

Trigger behavior when an HTML element is altered using AngularJS

I am currently developing an on-page JS application using Angular, which will be seamlessly integrated into various pages of our main website. The app is embedded on our page using the following code snippet: <div class="app-video-list" ng-app="videoL ...

Using Key Press to Rotate Messages - Jquery

Need help with rotating an array based on alphanumeric key presses? Check out the code snippet I've been working on below. Unfortunately, I'm having trouble getting the loop to function properly. Any suggestions or feedback would be greatly appre ...

What is the best way to create a dynamic text area that changes based on a dropdown selection?

I'm trying to create a feature on my form where selecting a retailer from a dropdown menu automatically generates a corresponding link next to the textbox. For example, if someone picks Best Buy, I want a link to bestbuy.com to show up immediately wit ...

The Rails application utilizes a background process application callback to initiate a specific event

I have a unique app that leverages the SuckerPunch gem and Carrierwave Backgrounder to efficiently upload and process images in the background of a cutting-edge rails application. As a user creates an instance of the Asset model, the image processing begin ...