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

Encountered issue with Ajax post request without any additional details provided

I could really use some assistance with this issue. It's strange, as Chrome doesn't seem to have the same problem - only Firefox does. Whenever I submit the form, Ajax creates tasks without any issues. My MySQL queries are running smoothly and I& ...

Strategies for preserving context throughout an Ajax request

In my project, I am looking to implement an Ajax call that will update a specific child element within the DOM based on the element clicked. Here is an example of the HTML structure: <div class="divClass"> <p class="pClass1">1</p> &l ...

Mozilla Firefox's webpage controls adapt according to the type of authentication being used

On my .NET MVC web page, I have 3 radio buttons for selecting a value on a form. However, in a specific test environment with two authentication methods (user/password or certificate), the radio buttons mysteriously change to checkboxes when the page loads ...

Incorporate a hanging indent within the text enclosed by the <li> element

(revised multiple times to enhance clarity) Disclaimer: I did not create the HTML code. Below is the structure of the HTML (please note that the links and text following them are on the same line): <li> <strong>Heading of section</str ...

"Utilizing AJAX for Data Retrieval in a Form with Dynamically Generated

Hey there, I'm trying to figure out how to make my ajax data call dynamic. Here's what I've attempted: var opt_name = $(".NAME").data('opt_name'); var opt_business = $(".BUSINESS").data('opt_business&ap ...

resolving date formatting issues in jQuery

The input field fromDate has a calendar pop up when focused for date selection. However, after selecting the date as 21/03/2014, the conversion to JSON date returns 20th March 2014: See my code snippet below: var fromDate = $("#fromDate").datepicker("get ...

"JQuery enables the dynamic cloning of form elements, allowing for attribute adjustments that can be easily reverted

I've been grappling with a puzzling issue recently. I used jQuery to clone a form and assigned IDs to the form elements to increase incrementally with each clone. However, following server validation errors (using Laravel), the IDs of the elements rev ...

Troubleshooting drag-and-drop functionality in a JavaScript HTML5 application resembling a Gmail upload interface

Here is a snapshot of my user interface: Each node in the tree structure is represented by an <li> element along with an <a> link. Furthermore, each folder serves as a dropzone for file uploads similar to the drag-and-drop feature found in Gm ...

There seems to be a connection issue between my Jquery and HTML, as they

I've hit a roadblock because my jQuery isn't connecting and I can't seem to figure out why. It's been stumping me for hours. Here is the HTML code snippet from exercise6.html: <!DOCTYPE html> <html lang="en> <h ...

The float:left property within a div is not behaving as anticipated

I am having trouble positioning my second div. In order to have 70% of my website for posts and 30% for a small text display, I created a new div. I believe the correct way to position it is by using "float: left" so that the div goes under the banner whe ...

Ideas for displaying or hiding columns, organizing rows, and keeping headers fixed in a vast data table using jQuery

My data table is massive, filled with an abundance of information. Firstly, I am looking to implement show/hide columns functionality. However, as the number of columns exceeds 10-12, the performance significantly decreases. To address this issue, I have ...

Arranging content within columns according to their column position

As I design a grid with three columns, each grid box contains a div with a maximum width of 280px. Sometimes the grid columns exceed this width. To achieve my desired layout, I aim to align the content in the grid boxes so that the left column aligns to th ...

Maintaining Styles After Focus is Removed in CSS: A Guide

The CSS that styles our buttons is as follows: .btn-outline-primary { color: blue; border: 1px solid blue; background: transparent; transition: all 0.3s ease 0s; } .btn-outline-primary:hover, .btn-outline-primary:focus { background: ...

How can I modify the font style in Bootstrap?

How can I integrate a custom open font into Bootstrap without using a CDN? Should I create a CSS rule to override Bootstrap's default font or locate the font files in Bootstrap and replace them with my desired font? ...

What are the steps to save data on a user's computer through a web browser?

Is it feasible to save data in the client's computer using a web browser and jQuery code to interact with the file system? ...

Concealing Website Elements with javascript based on class assignments

Despite my hesitation, I have to ask this question after unsuccessful searches in related articles. In my code, I have 7 nav links all with the same class. Due to the length of the HTML, I am looking for a way to hide contents until the link is clicked, an ...

Conceal the div that corresponds to the custom data attribute number located beneath the chosen

I am working on creating a filterable list that allows users to select a minimum and maximum number, hiding items that fall outside of the chosen range. Right now, I am concentrating on setting the minimum value. For this purpose, I have a selection box c ...

Looking to create a centered 'ul' using Bootstrap

I am looking to center the list with a specific width. body { background-color: rgb(26, 40, 114); } h1 { color: white; text-shadow: 7px 7px 10px black; } li { list-style: none; border-radius: 5px; border: 2px solid white; background-colo ...

Retrieving information from a database by employing AngularJS with the assistance of PHP

I am a beginner in using AngularJS and I am trying to retrieve data from a database using PHP. Here is the code I have tried: <html> <head> <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2 ...

Highlighting Navbar Items

Can anyone provide advice on how to highlight a navbar item when clicked? I'm unsure if I should use Angular or CSS for this. Any guidance would be greatly appreciated. <div class="collapse navbar-collapse" id="navbarNav"> <ul class ...