Home > Net >  Django Dropdown GET Option Data
Django Dropdown GET Option Data

Time:08-10

I wanted to get the selected text from the dropdown, But I am getting value if I use request.GET['Type']. I wanted to get Data001 instead of Value001

def index(request):
    print("The output: ",request.POST.get('Type'))
    return render(request,'index.html',content)
<div >
    <div >
        <label for="">Meeting Type</label>
        <select id="Type" name="Type" class='form-control'>
            <option disabled="disabled" selected="selected">Choose option</option>
            <option value='Value001'>Data001</option>
        </select>
    </div>
</div>
<div >
    <button data-text="Book" type="submit" name="action" value="book">
        <span>Book</span>
    </button>
</div>

Please note that, There are 30 dropdown options and I must use values in the dropdown. Kindly help me to get the selected option instead on value

CodePudding user response:

add a new input tag with hidden type. add onchange listener on select of id "Type" in callback function of event listener, replace the input tag value with the inner text of changed value in select

by this way, you can use it without ajax a

CodePudding user response:

So if this is using for filter purposes and you cannot change the values inside of option tags. Then you can use AJAX, you can get the .innerHTML of the selected option, and pass that as a dict to your views.py function

views.py

def ajax_option(request):
    print("The output: ",request.POST.get('Type'))
    return render(request,'ajax_option.html')

urls.py

path('ajax_option/', views.ajax_option, name="ajax_option"),

.html

<div >
        <div >
            <label for="">Meeting Type</label>
            <select name="Type" class='form-control' onchange="onchangehit(this.options[this.selectedIndex].text)">
                <option disabled="disabled" selected="selected">Choose option</option>
                <option value='Value001'>Data001</option>
                <option value='Value002'>Data002</option>
            </select>
        </div>
    </div>
    <div >
        <button data-text="Book" type="submit" name="action" value="book">
            <span>Book</span>
        </button>
    </div>

AJAX, right above the body tag

<script type="text/javascript">
            function onchangehit(data) {
                console.log(data);
                $.ajax({
                    type: "POST",
                    url: "{% url 'ajax_option' %}",
                    async: true,
                    data: {
                        Type: data,
                        csrfmiddlewaretoken: '{{ csrf_token }}',
                    },
                    success: function () {},
                    failure: function () {}
                });
            }
        </script>
  • Related