onchange不会通知(与选择字段一起使用)

时间:2019-05-19 03:16:02

标签: javascript html

我是网络开发的新手,我试图用flask和python构建一个Web应用程序。

从选择字段中选择某项时,我需要得到通知。

  • 我尝试抛出alert("test"),并显示了弹出窗口。

  • 我的第二次尝试是设置onchange="this.form.submit()"

  • 我的第三次尝试是设置onchange="document.getElementById('model_form').submit()"

但是没有任何反应,表单没有提交。

我在浏览器控制台中看到了以下例外情况:

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

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

这是通过烧瓶呈现的html代码:

<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>

保存按钮可以正常工作并提交表单。从选择字段中选择某项时如何获得通知?

1 个答案:

答案 0 :(得分: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>