How to get selected label text from django_autocomplete_light widget in javascript

34 Views Asked by At

I would like to get the selected label text (which is not the same as value) from dal widget in javascript function which is a side function and does not handle events from this widget. This must be the version of dal I am using: 3.8.1.

Firstly I noticed that event handler for dal widget receives a different object than what I get using document.getElementById(), not sure why.. This is how I can get value in a handler:

    function dal_onchange(name){
            var val = $(`#id_${name}`)

vs in a "side" function (somehow I cannot use $(`#id...) syntax, not sure why):

dal = document.getElementById('id_'+name)
var val = dal.value

However in either function it is not clear how to get label text and not value. The difference is that value is some id while label text is the text for this id. My dal view class has 2 methods defined:

class MyAutocomplete(autocomplete.Select2QuerySetView):
#...
    def get_result_value(self, item):
        return item.id

    def get_result_label(self, item):
        return item.text

Form:

myfield = forms.CharField(required=False, max_length=64, widget=autocomplete.Select2(url='/my-autocomplete-id/%d' % param, attrs={'class': 'form-control form-control-sm'}))

So in javascript I would like to get what would have been returned by get_result_label (I know javascript cannot call that function but I mean the data that it returns). The widget is not configured to take a new value and it is not possible to select multiple values.

So the only working option I have found so far was:

    function get_dal_selected_text(name){
        a = document.getElementById(name)
        if (a != null && a.value != null && a.selectedOptions != null && a.selectedOptions[0] != null) {
        return a.selectedOptions[0].innerText
        } else {
        return null
        }
    }

But I was using debugger to find it as there does not seem to be any documentation on this aspect. Actually there is a field "label" on the object but somehow it gets text values appending to it as you select different values in dropdown while what I want is the currently selected one. I have very little experience in js and surely may be missing some concepts. Is there a better way to do it?

0

There are 0 best solutions below