Combining Django with the power of JavaScript

I'm currently working on a project that involves creating a dynamic list using radio buttons. While I have been successful in retrieving the values for the list, I am facing difficulty in displaying it on the webpage.

Below is the JavaScript code snippet:

$(document).ready(function() {
    $("select[name=city]").change(function() {
        if ($(this).val() == '') {
            $("select[name=term]").html("<option>Select a frequency</option>");
            $("select[name=term]").attr('disabled', true);
        }
        else {
            var url = "/locality/city/" + Number($(this).val());
            console.log(url)

            $.getJSON(url, function(frequency_list) {
                var li = '<ul id="id_term"><li><label><input id="id_term_0" type="radio" value="-1" name="term"></input>None</label></li>'

                for (var i = 0; i < frequency_list.length; i++) {
                    // console.log(frequency_list[i][0],frequency_list[i][0]);
                    var id = "id_term_" + String(i)
                    li += '<li><label><input id='+String(id)+ ' type="radio" value='+frequency_list[i][0]+ ' name="term"></input>'+frequency_list[i][1]+'</label></li>'
                    console.log(li);
                }

                li +='</ul>'
                $("select[name=term]").html(li);
                // $("select[name=term] li:first").attr('selected', 'selected');
                $("select[name=term]").attr('disabled', false);
            });
        }
    });

    $("select[name=term]").change(function(vent) {
        if ($(this).val() == -1) {
            return;
        }
    });
});

Here are the form definitions:

class CityForm(forms.Form):
    city = forms.ModelChoiceField(queryset=City.objects.all().filter(tagged=True))

class FrequencyForm(CityForm):
    """
    Generates a form consisting of a list of trigrams, bigrams and unigrams in ratio 8:8:2
    """

    def __init__(self, *args, **kwargs):
        super(FrequencyForm, self).__init__(*args, **kwargs)
        self.frequency_list = [('-1','None')]
        self.fields['term'] = forms.ChoiceField(choices=self.frequency_list, required=True, widget=forms.RadioSelect())

Answer №1

If your list is successfully retrieved from the getJSON call, the issue may arise when attempting to insert content that is not an <option> within a <select> element. Refer to the specifications for the <select> element here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select It explicitly states:

Permitted content Zero or more option or optgroup elements.

Therefore, this particular line of code is unlikely to produce any desired outcome:

$("select[name=term]").html(li);

Consider adding the content afterwards or creating a new element that is not a select to contain your list.

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

Converting date string to a new format is not supported by moment js

Having some trouble with formatting dates for MySQL insertion. Here is the current HTML structure: <strong id="ut-open-date">27/06/2014</strong> I need to convert the date format to "YYYY-MM-DD" using moment.js library. My code snippet is as ...

What could be causing the dropdown options to update in the source code upon the Ajax call, but not reflect in the user interface?

My Django dropdown buttons are supposed to be initially empty, but upon calling a script to fetch the drop-down options, I encounter a problem. Although I can see the options populating in the source code, they do not show up in the UI when I click on the ...

"Dealing with Cross-Site Request Forgery in React Native and Django

After updating my React Native version from 0.67.0 to 0.72.6, I'm still utilizing Django 3.1.2 for my backend system. For handling sessions, I am using the default method provided by Django. Currently, I have a CSRF token stored in Asynchronous storag ...

Is there a way to render React components without using the JSX format?

I have been attempting to create a "smart" popup component that can display other components within itself. However, I am facing issues with my implementation as it is not functioning correctly. My approach involves using Redux to manage the state of the ...

Enhancing web pages using PHP method progress tracking

I am in the process of creating a basic import wizard and I would like to incorporate a notification feature that displays the progress of each method. For example, I have the following methods: public function mainFunction() { $this->firstStep(); ...

CSS Troubleshooting: oversized div

I want to adjust the size of my lightbox, but I'm facing some issues. When I set max-width: 100%, the images appear too large for PC screens (img) and too small for cellphones (img). Conversely, with a max-width: 50% setting, the images are just right ...

Storing API data in localStorage using VueJS: A step-by-step guide

As I work on practicing building a simple SPA with VueJS, one of my current tasks involves listening to an API and storing certain data in the browser's localStorage. However, my experience with VueJS is still limited, so I'm unsure about how to ...

What is the reason for the display of the option "admin | log entry | Can modify log entry"?

Can someone explain what a log entry in the Django admin panel is? I see the option to give my users log entry privileges, but I haven't set up any Logging model yet (mainly because I'm not sure what it's for). Some people suggest that log ...

Make text come to life as the user scrolls across a fixed positioned div

As the user scrolls, I am attempting to animate four headings. First, I create a sticky positioned div. Then, as the user scrolls over the headings, each one toggles the class .active sequentially, with the last one remaining visible and the scrolling cont ...

Displaying Sweetalert2 textarea inputs in an email

How can I capture the user inputs from a textarea in my code? Here are the details: https://i.sstatic.net/trG1E.gif This is my JavaScript code: $('#sad').on('click', function() { const sad = $('#sad').val(); con ...

Tips for resolving this JavaScript conditional statement

Can you help me understand how to make this if statement true and show an alert message? I'm unsure about the significance of 0x4, 0x3, and 0x05. How can we modify this code to trigger the alert? var Ft32A = [ function (x,y) {return x+y}, f ...

VueJS avoids displaying a specific data in every iteration of a v-for loop

Presented below is the code that I have managed to successfully get working: <span v-for="(item, index) in storedUserItems"> <template v-if="item.strength"> <img @mouseover="itemInfo(item, index)" style="padding: 5px;b ...

Navigating a collection of objects in JavaScript: A step-by-step guide

My data consists of objects in an array with the following structure: [{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}]; To clean up the array, I'm using this code: ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...

Trouble setting YouTube URL with jQuery iframe

I need help with embedding a YouTube video using jQuery. Below is the HTML code I have: <iframe class="embed-responsive-item" id="placeYoutubeVideo" style="display:none" src="#" style="display:none" allowfullscreen></iframe> In my j ...

Using Python Django to extract and process RSS XML data

I'm currently working on parsing 3 distinct RSS sources. Here are the URLs of these sources: https://www.nba.com/bucks/rss.xml http://www.espn.com/espn/rss/ncb/news http://rss.nytimes.com/services/xml/rss/nyt/ProBasketball.xml Despite some minor dif ...

What is the best way to ensure that a form filled out in Backbone is validated?

Recently, I created a new form that saves temporarily, but I am facing an issue where I want it to only update when validated, otherwise display errors. This problem arises during the view section for the saveEdits event. Any suggestions on what might be g ...

Leverage session functionality in Django's detailview to track and tally pageviews

I'm currently working on a feature to track the number of visits to a specific view. My goal is to increment the counter by 1 every time someone accesses the view, and then automatically update the "visits" field on the model with the latest count. Ho ...

What's the reason the bootstrap tooltip style isn't displaying?

Seeking assistance with styling text in a bootstrap tooltip. My request is straightforward: I would like the text in the tooltip on the first button to be displayed in red color. I have used data-html="true" attribute to allow HTML in the tooltip. Howev ...

Sending a Variety of Data to PHP: A Guide to Posting Multiple Data Types

Struggling with a dilemma at the moment, Currently, I am successfully sending JSON data to a PHP page, but I also need to include a variable in the same post request and I'm unsure of how to do so. Below is the code I'm currently using: $.ajax ...