What is the best way to create an input or form that is based on a select menu (dropdown list)?

I am currently developing a grading system and working on the form where users enter students' results. The form includes two dropdown lists (classroom, students) that are interdependent. My challenge lies in...

  • When the user selects a classroom, the second dropdown menu should display only the students in that particular class. I have already addressed this issue. However, my current roadblock is ensuring that input fields appear for each subject a student is studying, allowing the user to enter grades specific to that student.

For example, if I choose classroom 1b and select student Mary - if Mary studies 5 subjects, then 5 input fields should appear for me to enter the marks for each subject.

View a demonstration of what I am explaining through this video link

Models.py

    
        Class Classroom(models.Models): name = models.charfield()
    
        Class marks (models.Models): classroom = models.foreignkey(Classroom) Grade = models.Floatfield()

HTML Form

    <div class="container-fluid">
        <form id="result-form" method="post">
            {% csrf_token %}
            <!-- Modal -->
    
            <div class="modal-header">
                <h5 class="modal-title" id="staticBackdropLabel"> {% block modal-title%} Add Result {% endblock%}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12" id="msg8" style="font-size: 2rem; color:rgb(255, 144, 47)"></div>
    
                    <div class="col-md-12 form-group p-2">
                        <label class="form-label">Class Name</label>
                        {% render_field form.room class+="form-control" %}
                    </div>
    
                    <div class="col-md-12 form-group p-2">
                        <label class="form-label">Exam Name</label>
                        {% render_field form.exam class+="form-control" %}
    
                    </div>
    
                    <div class="col-md-12 form-group p-2">
                        <label class="form-label">Student</label>
                        {% render_field form.student class+="form-control select2" %}
                    </div>
                 <div class="hidden" id="subject-fields"></div>
    
                    <div class="form-group mb-3 pt-2">
                        <button type="button" id="resBtn" class="btn btn-info" title="Add">Submit</button>
                    </div>
                </div>
            </div>
    
        </form>
    </div>
    
    {% block script%}
    
                
   
    
    {% endblock%

Script

    $(document).on('click', '#submit-btn', function(event){
            var response_data = []
            var subject_name= $('.course');
            var subject_objs = $('.subject_id');
    

for(i=0;i<subject_name.length;i++){
        
        var subject_id = $(subject_objs[i]).find('input').val();
       
            var grade_input = {
                
                "Marks": subject_id,
                
            }
            response_data.push(grade_input);
        }
        $.ajax({
            type: "POST",
            url: "{% url 'marks' %}",
            data: response_data,
            success: function(response){
                alert("Success");
            }
        });
    });

This is how your view should look like.

def question_choice_view(request): if request.method == "POST": question_choice_data = request.POST['data']

Answer №1

I am not a fan of jQuery. If I were to handle the student form, I would use an event listener with

.addEventListener('change', (event)
Learn more. This way, a function would be triggered whenever there is a change in the select option. By capturing the selected values for classroom and student name, a request can be made to fetch subject names for the chosen student. Upon receiving a successful response, I would dynamically insert the subject fields into the DOM using JavaScript.

**

function createInput(item) {
  // Function to create a new input based on the item
  var newLabel = ' <br><label for="$item-mark">$item:</label>'
  var newInput = '<input type="text" id="$item-mark-id" name="$item-mark"><br><br>';
  newLabel = newLabel.replaceAll("$item", item)
  newInput = newInput.replaceAll("$item", item)
  newInput = newLabel + newInput
  var studInput = document.getElementById("student-id");
  studInput.insertAdjacentHTML('afterend', newInput);
}

function cleanOldInputs(item) {
  var oldElement = item + "-mark-id"
  oldElement = document.getElementById(oldElement)
  if (oldElement) {
    oldElement.previousSibling.remove()
    oldElement.remove()
  } else {}
}

function getAPIcall() {
  var responseObject = ["writing", "creativity"];
  responseObject.forEach(item => {
    cleanOldInputs(item)
    createInput(item)
  })
}


var studentSelect = document.getElementById("student-id");

studentSelect.addEventListener("click", function() {
  getAPIcall()
});
<form action="/action_page.php">

  <label for="student">Choose a student:</label>

  <select name="student" id="student-id">
    <option value="harry">harry</option>
    <option value="ivy">ivy</option>
  </select>
</form>

Quick and dirty**

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

What is the best way to eliminate a specific value within a flatmap?

This is the flatMap: const choices = names.flatMap( (item) => item.name + " - " + item.size + "- " + item.category ); console.log(choices): https://i.stack.imgur.com/MO4b1.png If the item.category is equal to S-XL, how can ...

Transforming DOM elements into Objects

Here are some values that I have: <input name="Document[0][category]" value="12" type="text"> <input name="Document[0][filename]" value="abca.png" type="text" > I am looking for a way to convert them into an object using JavaScript or jQuer ...

Steps for creating a read-only field in a CreateView

As a beginner in Django, I am attempting to set a 'price' field for an order as read-only. My understanding is that this cannot be accomplished within the model itself but rather requires manipulation within a form. Using a CreateView generic vi ...

Exploring the Possibilities: Combining Django Rest Framework with Vue on Heroku

A project has been developed with Django (specifically DRF API) and Vue js with the following structure: root_directory/ ├── project_name/ │ ├── settings.py │ ├── ... ├── front_end/ │ ├── ... vue files generated w ...

Is there a way to automate the verification of attribute existence in the class of my Django model when used in the __str__ method?

I recently encountered an issue in my Django 2.2 project where I renamed an attribute in a django.db.models.Model class but forgot to update the reference in the __str__ method of the same class. This mistake went unnoticed until I was testing something ...

Ways to create a variable in a function that can adapt without being tied to a variable that changes

Apologies for the vague title, but I am uncertain of the correct term for my issue. I am working on dynamically generating a table of clickable elements using for loops in JavaScript. Each element, when clicked, should execute the same function but with di ...

Display a subset of my Django models data on the Admin interface

Here is my database model: class Restaurant(models.Model): email_sent = models.BooleanField(null=True, default=False) rest_owner = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='rest_owner') is_approved = models.B ...

Is there a jQuery tool that can effortlessly add items to a list element?

I'm currently developing a task management application on the web. I have a textarea where users can input tasks, and when they press enter, it should automatically be added to a list element (li). The adding functionality works, but only after refres ...

I am experiencing issues with icons not loading correctly after changing my module, with error messages indicating issues with cross-origin

Exploring various online tutorials to master the art of Angular programming has been quite an adventure for me. One tutorial introduced a module defined in this manner: .module('MyApp') However, any attempt to modify the name resulted in an er ...

Encountering a "Cannot create foreign key constraint" error in Django during the makemigrations process

Currently, I am utilizing Django version 1.9.5 and Python version 2.7 with MySQL as my database management system. Upon attempting to make migrations, I encountered the following error: "Cannot add foreign key constraint" This issue arises when I try t ...

When trying to console log a selected date, the output displays as undefined

<div class='col-sm-6'> <input [(ngModel)]="date" id="date" name="date" class="form-control" required/> </div> $(function () { $('#date').datetimepicker({ format: 'DD/MM/YYYY hh:mm' } ...

How to remove cookies from my Chrome web driver using Python and Selenium?

I am currently attempting to clear the cookies in my Chrome browser using WebDriver from Selenium, but I am struggling to find solutions that are specifically tailored for the Chrome driver. Can anyone provide guidance on how to effectively clear the cac ...

Displaying a static image on an HTML5 canvas without any movement

As a novice in canvas game development, I must apologize for my lack of knowledge. I have an image with dimensions 2048px width and 1536px height that needs to be placed within a canvas (the width and height vary on different devices). While I am able to ...

The deployment of the Firebase function encountered an issue

For some reason, the Node.js command prompt seems to be ignoring this particular function despite other functions being deployed without any errors. var database = admin.database(); var postsRef = database.ref("/posts"); postsRef.on('child_added&apo ...

Creating virtual hover effects on Android browsers for touch events

My Wordpress website is currently utilizing Superfish 1.5.4 to display menu items. The menu on my site includes several main menu items, which are clickable pages, and hovering over these main items should reveal sub-menu options. When I hover over a mai ...

Can anyone identify the result produced by this line of code? Utilizing the $.get method to access "http://192.168.4.1:80/" with the parameter {pin:p}

Can anyone explain the output of this line of code? $.get("http://192.168.4.1:80/", {pin:p}); I understand that it is an Ajax code that sends data through a GET request, but I am trying to manually send the same data like this ".../pin:13" or "", however ...

The progress bar seems to be malfunctioning

Need help with my progress bar, it's not working properly. Can someone assist me? var x = document.getElementById("p_bar"); for(var i = 0; i < 100; i++) { var wid; wid=1; if(wid == 800) break; else wid+=8; x.style.width=wid+" ...

Display a Popup at 5PM without the need for a page refresh, updating in real-time

After searching extensively online, I was unable to find a suitable solution for my issue. What I am aiming for is to have a popup appear on my page every day at 5:00 PM without the need to refresh the page. If I happen to access the page before 5:00 PM an ...

Where can I locate information on using the .get method?

Recently, I encountered a code snippet on this site that helped me resolve an issue. The individual who provided the code utilized a .GET method that was unfamiliar to me. Here's a sample snippet: If you'd like to see the complete code, you can ...

`Turn nested JSON into a formatted list using jquery`

I am currently facing two challenges: I am having trouble with the HTML structure, as shown in the image below Current HTML structure: https://i.stack.imgur.com/GH46J.png Desired HTML structure: https://i.stack.imgur.com/Dq3Gn.png How can I create d ...