[Answer]-How do you submit the selected value in a dropdown via ajax in Django

1👍

Here’s an example using JQuery that places an event handler on the select widget that will call your Django view when the user makes a selection. In this example the selected name is being appended to the URL so that Django can grab it with the following regex in urls.py:

url(r'^path_to_app/(?P<name>\w+)$', 'app.views.function'),

Here’s an example:

<select id="chooseme">
<option>--select a name--</option>
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {

    $('#chooseme').change(function(){
        var name = document.getElementById("chooseme").value;
        $.get('/path_to_app/' + name, function(data){
               // do something here with a return value data, if desired
        });
    });
});
</script>

0👍

Check that:

<select id="select_form">
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option> 
</select>

var name = $('#select_form').find(":selected").text();
var url = 'your_url_here'+userName+'/';
   $.get(url, function(data)
   {
      //do something with data
   })

0👍

I tried like this for the following select dropdown:

<select id="select_dropdown">
<option value='joshua'>joshua</option>
<option value='peter'>peter</option>
....
....
</select>

<script>

$(document).ready(function(){

 $('#select_dropdown').change(function(){
    var e = document.getElementById("select_dropdown");
    var value = e.options[e.selectedIndex].value;

    $.ajax({
        url: "your-url",
        type: "post",
        data: value,
        success: function(data) {

           console.log(data);
        }});

});

</script>
👤ruddra

Leave a comment