What is the best way to reference a dynamic ID in JavaScript when clicking for an action on a different

Here is my HTML code snippet:

<table>
      <tr>
          <td>
              @Html.DropDownList("Statues", (SelectList)ViewBag.UserType, string.Empty, new { @class = "NewIDCn",@id = "name1" })
          </td>
          <td>
              <a class = "UpdateU" href="@Url.Action("Update", "UserPromoted", new { id = item.UserID})">Update</a>
         </td>
      </tr>
      <tr>
          <td>
               @Html.DropDownList("Statues", (SelectList)ViewBag.UserType, string.Empty, new { @class = "NewIDCn",@id = "name2" })
         </td>
         <td>
               <a class = "UpdateU" href="@Url.Action("Update", "UserPromoted", new { id = item.UserID})">Update</a>
         </td>
     </tr>
</table>

And below is the included script block with JavaScript:

<script type="text/jscript">
    $(document).ready(function () {
        var i = 0;
        $('.NewIDCn').each(function () {
            i++;
            var newID = 'name' + i;
            $(this).attr('id', newID);
            $(this).val(i);
        });
    });
        $(function () {
            $('.UpdateU').click(function () {
                var name = $('#name').val();
                this.href = this.href + '?UserType=' + encodeURIComponent(name);
            });
        });
</script>

Also, here is a glimpse at my Controller function:

 public ActionResult Update(string id, string UserType)

         {
                    query = "UPDATE    tblUserRegister SET          UserType = ' " + UserType + "' WHERE     (UserID = '" + id + "')";
                    cmd = new SqlCommand(query, conn);
                    cmd.ExecuteNonQuery();
         }

The document.ready function aims to dynamically increment the ID of elements named name(name1,name2). When I trigger the URL action, the statue ID should be updated to reflect the User Type. How can I ensure that this happens correctly and return both the ID name and User Type to the controller for processing?

Answer №1

There are multiple ways to accomplish this task. You can try the following method:

First, add some classes to the tr element like this:

<table>
    <tr class="t-row">
        <td>
            @Html.DropDownList("Statues", (SelectList)ViewBag.UserType, string.Empty, new { @class = "NewIDCn",@id = "name1" })
        </td>
        <td> <a class="UpdateU" href="@Url.Action(" Update ", "UserPromoted ", new { id = item.UserID})">Update</a> </td>
    </tr>
    <tr class="t-row">
        <td>
            @Html.DropDownList("Statues", (SelectList)ViewBag.UserType, string.Empty, new { @class = "NewIDCn",@id = "name2" })
        </td>
        <td> <a class="UpdateU" href="@Url.Action(" Update ", "UserPromoted ", new { id = item.UserID})">Update</a> </td>
    </tr>
</table>

Next, update your script as shown below:

 $(document).ready(function () {
    $(document).off("click", ".UpdateU").on("click", ".UpdateU", function (event) {
        var url = $(event.target).attr("href");
        var val = $(this).parents(".t-row").find("select").val();
        var newUrl = url +'?UserType=' + encodeURIComponent(val);
        alert(newUrl );
        event.stopPropagation();
        return false;
    });
});

newUrl will serve as the URL for the controller.

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

How can I handle invalid URLs in AngularJS to return a 404 status code?

We have a website developed using AngularJS and deployed on an IIS web server. The site is a single page application with only one page, Index.html. To improve SEO, we are utilizing prerender.io for rendering. In order to rewrite every URL to the root pat ...

What sets Angular Material apart from AngularJS Material when it comes to responsiveness?

I am facing a dilemma in choosing a framework for my application. In my search, I came across Angular Material and AngularJS Material. Although both frameworks are developed by Google (correct me if I'm wrong), they seem to serve the same purpose of r ...

The angular view is lacking a CSS class

index.html: <div ng-view="myview.html"></div> myview.html: <table class="table table-striped table-hover"> <tr> <td>Name</td> <td>Product</td> </tr> <tr ng-repeat="deal in deals" class="clickableR ...

Seeking an AJAX jQuery method for retrieving the values of four fields and transmitting them to the server

My MVC application is in need of extracting values from a variable number of field values, including: field_1, field_2 .. field_4 The goal is to send these values to the controller and update the text of a Div element based on the response. I have limit ...

Invoke data-id when the ajax call is successful

Initially, there was a smoothly working "like button" with the following appearance: <a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span ...

Shut down the angular modal

I am currently learning AngularJS and I find myself working on an application that utilizes both angular modal and jqGrid. (I understand this may not be the ideal setup, but for now, I have to make it work with both.) The content of my modal is loaded usi ...

Utilize Selenium to extract information from a webpage, including content that is dynamically generated through JavaScript

Currently, I am facing a dilemma: my desire is to extract information from a webpage (for example, this one) regarding the apps that are available, and then store this data into a database. In my quest to achieve this task, I have opted to use crawler4j t ...

Steps for positioning an item above CardActionArea

I would like to figure out how to position an object above the CardActionArea. For example, if I have a button on top of the CardActionArea and click on that button, both the CardAction and Button actions will be triggered simultaneously. I want it so that ...

Issues with Node AssertionErrors cause failures to be silent and prevent proper error output

I am facing an issue with a particular method in my code. The code snippet is as follows: console.log('Trouble spot here') assert(false) console.log('Will this show up?') Upon running this code within my application, the followi ...

Issue with horizontal scrolling in ng-scrollbars occurs when scrolling from right to left

We are currently developing a single page application that supports two languages, one being right to left and the other left to right. For scrolling functionality, we have implemented ng-scrollbars, an Angularjs wrapper for the malihu-custom-scrollbar-pl ...

Toggle the ASP validation control using JavaScript

I am looking to control the validation of my form using JavaScript. When a user clicks on a radio button in a list (yes or no), 2-3 rows are displayed. If the user selects "Yes," they must enter input into a textbox in one of those rows. To enforce this, ...

The link function of an AngularJs directive is unable to access the attribute value

I am facing an issue with a directive in AngularJS. return { restrict: _restrict, link: function (scope, element, attrs) { $timeout(LinkPre, 0); //Calling a scoped method }, templateUrl: Con ...

Having trouble with AES decryption on my nodeJS/ExpressJS server backend

Looking to decipher data post retrieval from mongoDb. The retrieved data comprises encrypted and unencrypted sections. app.get("/receive", async (req, res) => { try { const data = await UploadData.find(); const decryptedData = data. ...

Upon initial page load, React JS is unable to fetch the data but it functions correctly when triggered by a click

Here is the code I am working with: var CommonHeader = require('./header/CommonHeader.jsx'); var ListOptions = require('./header/ListOptions.jsx'); var SortableTable = require('../shared/SortableTable.jsx'); var ColumnDefinit ...

Implementing a 1-second delay in a Vue.js delete request

I have items that are retrieved through API calls and users can add them to their cart. They also have the option to delete items from the cart, but I want the item to be visually removed from the front-end after 1 second because of an animation on the del ...

Just updated to Angular 10, encountered issue: Unable to modify the read-only property 'listName' of an object

After updating my Angular project from version 8 to version 10, I encountered an error while trying to edit an input field in a Material Dialog. The error message displayed is as follows: ERROR TypeError: Cannot assign to read only property 'listName& ...

Assign an identification number to a column within a foreach loop in MVC4

In my MVC4 project, I am creating a dynamic table using the following code: foreach(var item in model.details) { <tr> <td> @item.status </td> </tr> } I'm looking for a way to assign an ID ...

What is the correct placement for $.validator.setDefaults({ onkeyup: false }) in order to deactivate MVC3 onKeyup for the Remote attribute?

After coming across various solutions on how to disable the onKeyup feature of MVC3 Remote Validator, I noticed that many suggest using the following code: $.validator.setDefaults({ onkeyup: false }); However, I'm in a dilemma about where to place t ...

Unable to view HTML without an internet connection

I have encountered an issue where my files work fine when uploaded to an online server, but do not work when accessed locally offline. An error message about a cross-origin issue appears. How can I solve this problem? Error message: Security Error: Conte ...

Calculating the combined total and mean values within an object using JavaScript

I have a set of data in the following format: { "Dates": ["January", "January", "March", "March", "March", "November", "November"], "Values": [45.6, 0.5, 59.3, 46.56, ...