Conceal or reveal radio buttons according to information in a table

How can I dynamically add and remove values from a table based on radio button selections? My goal is to add the selected value to the table and hide it from the radio button list, and if the value is deleted from the table, I want to show it back in the radio button list. Any suggestions or ideas on how to achieve this?

Radio Button List:

foreach (var item in Model.ServicesList)
{
    <div class="col-md-4">
        <div class="funkyradio-default">
            @Html.RadioButtonFor(model => model.SelectedServiceID, @item.ServiceID, new { @class = "form-control ", @id = @item.ServiceID, @required = "required", title = "Select Service" })
            <label name="ServiceName" id="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3a09681859a9096bd929e96acb39a87969edda09681859a9096bab7">[email protected]</a>" for="@item.ServiceID"> @item.ServiceName</label>

            @Html.ValidationMessageFor(model => model.SelectedServiceID, "", new { @class = "validation-label" })
        </div>
    </div>
}

Table:

<div class="row ">
    <div class="col-6">
        <table class="table main-table" id="ServicesTable">
        </table>
    </div>

JQuery Function:

function AddNewService() {
    var SelectedServiceID = $('[name="SelectedServiceID"]:checked').val();

    $.ajax({
        type: "Post",
        url: '/IndividualLicense/CheckServiceRequirment',
        data: { "SelectedServiceID": $('[name="SelectedServiceID"]:checked').val(), "MainServiceID": $('#MainServiceID').val() },
        success: function(data) {

            if (data.Result == true) {

                var table = document.getElementById("ServicesTable");

                var Services = [];

                Services.push({
                    'SelectedServiceID': SelectedServiceID,
                    'MainServiceID': $("#MainServiceID").val(),
                    'ServiceName': $("#ServiceName_" + SelectedServiceID).text(),

                });

                for (i = 0; i < Services.length; i++) {
                    let content = "<tr style='border-bottom: 1px solid #dee2e6;'>";
                    for (j = 0; j < Services.length; j++) {
                        content += '<td>' + Services[j].ServiceName + '</td>';
                        content += "<td><div><button id='" + Services[j].SelectedServiceID + "' class='btn btn-view delete' name='delete' type='button'>Delete</button></div></td>";
                        content += '<td style="display:none">' + Services[j].SelectedServiceID + '</td>';
                        content += '<td style="display:none">' + Services[j].MainServiceID + '</td>';

                    }
                    content += "</tr>";

                    $('#ServicesTable').append(content);
                }
            }
    
        });
}

Answer №1

To easily achieve this, you can utilize the data attribute as demonstrated in the following example:

$(document).ready(() => {
  // checkbox change event when input checked/unchecked
  $(document).on('change', 'input:checkbox' , (e) => {
    if(e.target.checked){  // if checked
      const serviceID = $(e.target).val();  //get its value
      $(e.target).closest('li').remove();   // remove the closest li
      $('table').append(rowHTML(serviceID)); // append to the table with id value
    }
  });
  
  // delete the row
  $(document).on('click' , ".btn.delete" , (e) => {
    const get_row = $(e.target).closest('tr');  // get closest row/tr
    const get_row_id = get_row.attr('data-serviceID-row'); // get the data-serviceID-row from <tr data-serviceID-row="5">
    get_row.remove(); // remove the row
    $('ul').append(inputHTML(get_row_id)); // append the li with input to the ul
  });
});

// The HTML 
function rowHTML(serviceID){
  return '<tr data-serviceID-row="'+ serviceID +'"><td>Service ID '+ serviceID +'</td><td><span class="btn delete">Delete</span></td></tr>';
}
function inputHTML(serviceID){
  return '<li><input type="checkbox" value="'+ serviceID +'" />Service ID '+ serviceID +'</li>';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr data-serviceID-row="5">
    <td>Service ID 5</td>
    <td><span class="btn delete">Delete</span></td>
  </tr>
</table>

<h3>CheckBoxes</h3>
<ul>
  <li><input type="checkbox" value="1"/>Service ID 1</li>
  <li><input type="checkbox" value="2"/>Service ID 2</li>
  <li><input type="checkbox" value="3"/>Service ID 3</li>
  <li><input type="checkbox" value="4"/>Service ID 4</li>
</ul>

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

I encountered an error with the TS1003 code in Angular because an identifier was expected on the throw import statement. Upon further investigation, I realized that the issue originated from

I came across this piece of code: import { Observable, throw} from 'rxjs'; An error message popped up saying identifier expected: ERROR in config/config.service.ts(3,22): error TS1003: Identifier expected. The error appears to be related to ...

No matter how hard I try, the async function within the React Component keeps returning 'Promise {<pending>}' consistently

Currently, I'm facing an issue where running an asynchronous function inside a functional component in React (NextJS) results in the function returning a pending promise: Promise {<pending>}. Oddly enough, fetching data from a dummy API works pe ...

What is the most efficient method for examining dependencies in Yarn 2 (berry)?

Is there a way to check for vulnerabilities in Yarn 2 dependencies? In Yarn 1.x, you could run yarn audit, similar to npm audit. However, this command is not available in Yarn 2. According to this issue on the Yarn berry Github, it may not be implemented ( ...

Make the background image within a button stretch to completely cover the button

I need assistance with creating a button that has a large image as its background. The challenge I'm facing is that the image fits vertically within the button, but horizontally it repeats unless I use 'no-repeat', which leaves empty space i ...

Creating a dynamic div and populating it with data from various elements in separate xhtml files: a step-by-step guide

I am looking to dynamically add a div under the div tag with id "includedContent" in the code below. Additionally, I would like to modify the load method to accept an array of ids instead of a hardcoded Id(123) and display the data in the dynamically creat ...

Setting the endpoint address for the <service> in the WCF server's web.config file

Exploring the impact of the <service> section configuration with the endpoint address in the web.config file has sparked some interesting findings. By commenting out all available options and running my WCF on an ASP website project in Visual Studio, ...

Guide to showcasing a placeholder in MUI's Select component

How can I add the placeholder "Select a brand" to this select element? I've tried different options with no luck. Here is the code snippet I am working with: <FormControl fullWidth> <InputLabel id="demo-multiple-name-label" ...

Maintaining text color while adding a color overlay to a Bootstrap Jumbotron

After searching extensively, I couldn't find any mention of this particular issue. According to the Bootstrap 4.2 documentation on the Jumbotron, I constructed my div with an inline background image. However, when I attempted to apply an overlay on to ...

Gathering information from mapped objects when they are clicked in a React application

Do you know how to retrieve genre.id when a user clicks on a Button and triggers the onClick function? Your assistance is greatly appreciated. ... return ( <div className="App"> <Header /> <div className="A ...

The CustomValidator ClientValidationFunction will only activate on the second or subsequent submission if CheckBoxList is checked

I am encountering an issue with a user control that is dynamically added to pages on DNN. The user control is built on a customized version of CheckBoxList and includes a CustomValidator with ClientValidationFunction set to a javascript function. It works ...

Using asynchronous data in Angular 2 animations

Currently, I have developed a component that fetches a dataset of skills from my database. Each skill in the dataset contains a title and a percentage value. My objective is to set the initial width value of each div to 0% and then dynamically adjust it t ...

Positioning an Element on a Web Page in Real-Time

Trying to implement an Emoji picker in my React application, I have two toggle buttons on the page to show the picker. I want it to appear where the Toggle button is clicked - whether at the top or bottom of the page. The challenge is to ensure that the pi ...

Let's compare the usage of JavaScript's toUTCString() method with the concept of UTC date

When I fetch the expiry date time in UTC from the Authentication API along with a token, I use the npm jwt-decode package to extract the information. private setToken(value: string) { this._token = value; var decoded = jwt_decode(value); this._ ...

Expanding and shrinking the index within a specific circular boundary in JavaScript

I'm dealing with a circular range of ASCII values from a to z, where each letter corresponds to a number between 97 and 122. I have no issue with increasing the value within this range, but I am struggling when it comes to decreasing it. For example ...

Is it feasible to extract color information from Google Calendar using Fullcalendar jQuery?

Is there a way to automatically retrieve the color set on a Google calendar for events? While looking at gcal.js, I didn't find any information about this feature, but in Google's JSON API (json-c), there is a mention of color. Could it be possi ...

The function 'compilation.emitAsset' is not recognized by the sitemap-webpack-plugin

I'm currently working on setting up a sitemap for my live environment and I've encountered an issue while trying to utilize the sitemap-webpack-plugin. The error message I received is as follows: ERROR in TypeError: compilation.emitAsset is not a ...

Locate and substitute `?php` and `?` in a given string

I am facing a challenge with inserting a large string of valid HTML code into the DOM, as the string also includes PHP code. When Chrome renders the code, it automatically comments out the PHP sections. The PHP code is encapsulated in <?php ... ?>, s ...

When I separate the div into its own line in the HTML/CSS code, the behavior changes significantly

I'm encountering an issue with my HTML/CSS structure: .im-wrapper { width: 100%; height: 100%; position: fixed; overflow: hidden auto; top: 0; left: 0; } .im-backdrop { background-color: var(--darkblack); opacity: 80%; width: 1 ...

What steps can be taken to address an undefined error before the execution of useEffect?

Today I encountered a small issue with my online player. It's fetching songs from the database using useEffect and saving them in state like this: const [songs, setSongs] = useState([]); const [currentSong, setCurrentSong] = useState(songs[0]); a ...

What is causing the issue with useForm not being identified as a function?

error image Why is this error occurring when attempting to use useForm: ⨯ src\app\journal\page.tsx (18:53) @ useForm ⨯ TypeError: (0 , react_hook_form__WEBPACK_IMPORTED_MODULE_5__.useForm) is not a function at Page (./src/app/journal/pa ...