How do I update a form having select option in Flask (Python)

Question:

I have created a registration form in Flask which includes a drop-down menu for selecting a department. There are four options available in this menu. When a user selects a department, the selected value is correctly stored in a MySQL database. Now, I want to create an update page where users can modify their details. The department options on this page are static and are not being retrieved from the database. Is it possible to have the selected option in the drop-down menu pre-selected on this update page?

<div class="input-group" style="margin-bottom: 5px;">
  <label class="input-group-addon">Department:<span style="color: red">*</span> </label>
  <select name='employee_status' class="form-control">
    <OPTION selected value='Sales'>Sales</OPTION>
    <OPTION value='Marketing'>Marketing</OPTION>
    <OPTION value='Support'>Support</OPTION>
    <OPTION value='Development'>Development</OPTION>
  </select>
</div>

Thanks in advance.

Answers:

If you want to update your html code with Flask you can, but you have to return a new html template and I don’t think that the good way.

You can make an AJAX call to your Flask route, and on the success callback you can update directly your form with the values you want (Easier with jquery).

$.ajax({
  type     : 'POST',
  url      : '/updateForm',
  dataType : "json",
  contentType: 'application/json;charset=UTF-8',
  data     : JSON.stringify(dict_var),
  success : function (result) {
    $('.'+dict_var.form_name[result.value]).attr('selected','selected');
  },
  error : function (error) {
    console.log(error);
  }
});

With dict_var = {
‘name’ : form_name,
‘value’ : selected_value
}

Something like this 🙂

Peace

Answered By: SD3L
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.