"An Effective Method for Retrieving the ID of a Chosen Row within a Table through

Currently, the student information list is being generated. An option has been added to select a checkbox and click the "Add Teacher" button to include the name of the currently logged-in user in the teacher column. There is a need to apply an event to all selected rows by passing multiple values as parameters when multiple checkboxes are selected. I have searched for a solution but haven't found one yet, so any assistance would be greatly appreciated.

urls.py

path('student/add_teacher/<int:id>/', views.add_teacher)

views.py

def add_teacher(request, id):
    student = Student.objects.get(pk=id)
    student.teacher = request.user.name
    student.save()
    return HttpResponseRedirect(f'/student/')

student_list.html

<table id="student-list" class="maintable">
        <thead>
           <tr>
              <th>Name</th>
              <th>Age</th>
              <th>Register date</th>
              <th>Select</th>
          </tr>
        </thead>

        <tbody>
          {% for student in student %}
          <tr class="text-black tr-hover table-link text-center student" student-id="{{ student.id }}">
             <td>{{ student.name }}</td>
             <td>{{ student.age }}</td>
             <td>{{ student.register_date }}</td>
             <td><input type="checkbox"></td>
          </tr>
          {% endfor %}
        </tbody>
      </table>

      <button type="button" class="btn btn-secondary addteacher">Update Teacher</button>

student_function.js

$(function () {
        $('button.addteacher').click(function (e) {
        var elem = $(".maintable input:checked").parents("tr");
        var studentID = elem.attr('student-id');
        var updateTeacher = confirm("Are you sure you want to update?");
        if (updateTeacher) {
            window.location.href = 'student/add_teacher/' + studentID + '/';
        }
    });
});

Answer №1

sample templates:

<table id="person-list" class="datatable">
        <thead>
           <tr>
              <th>Full Name</th>
              <th>Age</th>
              <th>Registration Date</th>
              <th>Action</th>
          </tr>
        </thead>
        {% for person in people %}
        <tbody>
    
      <tr class="text-dark tr-effect table-link text-center member" id="{{ person.id }}">
         <td>{{ person.full_name }}</td>
         <td>{{ person.age }}</td>
         <td>{{ person.registration_date }}</td>
      <td>
 <button type="button" class="btn btn-primary addmember" person-id="{{ person.id }}">Update Member</button>
    </td>
<tr>
              
            </tbody>

    {% endfor %}
          </table>

javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$('.addmember').click(function (e) {
  
        var personID = $(this).attr('person-id');
      $.post("{% url 'update_member' %}",
           { 
         id:personID 
          },
function(data, status){
  // perform any desired action upon success
  $('#'+personID).hide();
  });
         
})
</script>

functions.py

def update_member(request):
    person_id = request.POST.get('id')
    // additional logic can be added here
    person = Person.objects.get(id=int(person_id))
    person.member_status = "Updated"
    person.save()
    return HttpResponseRedirect(f'/members/')

urls.py:

path('members/update_member/', views.update_member,name='update_member')

this is just a demonstration of the process.

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

Is it possible to determine the outcome of a JavaScript function using Python?

I am currently in the process of creating a web crawler. Extracting links from HTML is simple, but finding links that are generated by JavaScript proves to be more challenging for me. Is there a way to access the JavaScript output in order to determine w ...

Is it possible to specify the database connection to use in npm by setting an environment variable?

I have established a database connection in a JavaScript file. const dbCredentials = { user: 'something', host: 'localhost', database: 'something', password: 'something', port: 1111, }; export default d ...

Transmitting HTML content to the browser from the client using Node.js

Quoted from: Book - "Getting MEAN with Mongo, Express.." When it comes to responding to requests in your application by sending HTML to the browser, Express simplifies this process compared to native Node.js. With support for various templating e ...

Enhancing Google charts with vertical line effects on hover

I am currently working on a project using google line charts and an angularjs directive. I am trying to figure out how to display vertical lines on hover, similar to how it is done on Google Trends, instead of having fixed lines. However, I have not been a ...

Using Plotly.js within a deleted Vue.js component may result in displaying an incorrect chart

Issue I am facing a problem with deleting one of the components that contains a chart. Even after deleting the component, the chart remains visible. To see an example, check out this jsfiddle: https://jsfiddle.net/m4ywp5fc/4/ Solution Attempted I attem ...

How to execute a system command or external command in Node.js

I am encountering an issue with Node.js. When using Python, I would typically perform an external command execution like this: import subprocess subprocess.call("bower init", shell=True) Although I have explored child_process.exec and spawn in Node.js, I ...

What is the best way to implement TrackballControls with a dynamic target?

Is there a way to implement the three.js script TrackballControls on a moving object while still allowing the camera to zoom and rotate? For example, I want to track a moving planet with the camera while giving the user the freedom to zoom in and rotate ar ...

The time update in React Js is not showing on Material UI's DatePicker

Utilizing the Material UI KeyboardDatePicker in my application has proven to be quite tricky. When I select a date, the initial selection displays both the date and time correctly. However, after waiting for 1-2 minutes and selecting another date, the date ...

Utilizing the Vuetify pagination feature in your project

I am in need of some guidance regarding the configuration of vuetify pagination. I have a card component that I loop through, but I also want to implement pagination around it. Any insights on where to start would be greatly appreciated? <v-pagination ...

Creating a unique navigation route in React

My application has a consistent layout for all routes except one, which will be completely different from the rest. The entire application will include a menu, body, footer, etc. However, the one-off route should be standalone without these elements. How ...

How to eliminate space preceding a div using jQuery?

I am trying to modify the following code snippet: <div id="one">1</div> <div id="two">2</div> <div id="three">3</div> Is there a method for me to eliminate the space before div "three" in order to achieve this result: ...

Setting the default selected row to the first row in ag-Grid (Angular)

Is there a way to automatically select the first row in ag-grid when using it with Angular? If you're curious, here's some code that may help: https://stackblitz.com/edit/ag-grid-angular-hello-world-xabqct?file=src/app/app.component.ts I'm ...

When incorporating MDX and rehype-highlight on a next.js site to display MD with code snippets, a crash occurs due to Object.hasOwn

I'm encountering an issue with my setup that is based on examples from next.js and next-mdx-remote. Everything was working fine until I added rehypeHighlight to the rehypePlugins array, which resulted in this error. Any thoughts on why this could be h ...

The onChange event seems to be failing to activate during a jQuery / Ajax form submission

Differences in Form Submission Methods The onChange event functions correctly with the traditional Type and Action method in both Firefox and Chrome. <form name="frmname" action="./add_p.php" method="POST"> <div> <select name=" ...

Creating a simulation of a ReactJS form tag using TestUtils does not activate the `onSubmit` event

When attempting to simulate the onSubmit event on the form tag using Sinon to spy on the method, it appears that the method being spied on is not called at all. For reference, here's a JSFiddle. ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Unable to perform migration following makemigrations in Django

Hello everyone, I am new to this field. After running makemigrations and then migrate, I encountered an error code. I have tried to solve it but I am still stuck. Can someone please guide me? I have attached the error code below. (venv) C:\Users\ ...

Unexpected error when using Slack SDK's `client.conversations.open()` function: "User Not Found"

I am currently utilizing the Slack node SDK in an attempt to send private messages through a bot using user IDs: const client = new WebClient(process.env.SLACK_TOKEN); const sendMessage = async (userId) => { try { await client.conversations.open( ...

The onChange function in React is not behaving as I anticipated

Consider the following data structure for tables: an array of objects containing nested objects: [ { "1": { "1": "Item s ", "2": "Manufacturer ", "3" ...

Execution priority of Javascript and PHP in various browsers

I implemented a basic JavaScript function to prevent users from using special characters in the login form on my website: $("#login_button").click(function(){ formChecker(); }); function formChecker() { var checkLogin = docum ...