0

I'm a newby at web development and I have tried to build a web app with flask and python.

I need to get notified when something from the select field has been chosen.

  • I tried to throw an alert("test") and the popup is shown.

  • My second try was to set onchange="this.form.submit()"

  • My third try was to set onchange="document.getElementById('model_form').submit()"

But nothing happened, the form wasn't submitted.

I see in the browser console these exceptions:

Uncaught TypeError: document.getElementById(...).submit is not a function at 
HTMLSelectElement.onchange

Uncaught TypeError: this.form.submit is not a function at 
HTMLSelectElement.onchange

This is by flask rendered html code:

<form id="model_form" action="" method="post" enctype="multipart/form-data">
        <div class="table-responsive">
            <table class="table table-bordered">
                ...
            <td>
                <select id="myField" name="myField" onchange="this.form.submit()"><option value="b">b</option><option value="a">a</option></select>
               <span class="help-block"></span>

            </td>
                ...
                <div class="well well-sm">
        <button type="submit" class="btn  btn-sm btn-primary">Save
            <i class="fa fa-save"></i></button>
    </div>
</form>

Save button works pretty fine and submits the form. How can I get notified when something from the select field is chosen?

Christopher Bennett
  • 803
  • 1
  • 8
  • 20
lama1234
  • 19
  • 5

1 Answers1

0

The following snippet does exactly what you want.

At the javascript code i capture both elements and save them on variables. I add an on change event to the select element, the function responsible for handling the select change event logs the selected value on the console and calls the submit method of the Form element.

I hope this helps you.

const form = document.getElementById('model_form');
const select = document.getElementById('myField');

const handleSelectChange = function(e) {
  console.log(e.target.value);
  form.submit();
}

select.addEventListener('change', handleSelectChange);
<form id="model_form" action="" method="post" enctype="multipart/form-data">
        <div class="table-responsive">
            <table class="table table-bordered">
                ...
            <td>
                <select id="myField" name="myField"><option value="b">b</option><option value="a">a</option></select>
               <span class="help-block"></span>

            </td>
                ...
                <div class="well well-sm">
        <button type="submit" class="btn  btn-sm btn-primary">Save
            <i class="fa fa-save"></i></button>
    </div>
</form>
Ramon Portela
  • 419
  • 2
  • 8