Issue
I have a list of 6 elements. I get it as a dropdown through bootstrap-select
. I can receive element of list in the console only if the form is submitted for handling.
Main question is:
How to make it so that when I select an element, I can immediately get it(print it) in the console, before submitting the form?
app.py
description = ['one','two','three','four','five','six']
@app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
docs = request.form.getlist('sel')
print(docs)
return render_template('login.html', description=description)
return render_template('login.html', description=description)
login.html
<form action="" method="POST" class="form-inline">
<select id='sel' name='sel' class="selectpicker" multiple data-live-search="true">
{% for desc in description %}
<option value="{{desc}}">{{desc}}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-primary">Identify</button>
</form>
<script type="text/javascript">
$('select').selectpicker();
</script>
Solution
If you want to print in the console, you don’t need to work on the app.py
, however, you need to work on your login.html
.
To enable this, your answer is onchange
, which is predefined for the <select>
, captures your data when you select an option. No need to have a submit button either.
UPDATED ANSWER: The <p>
waits for the value, which is being set inside our function printValue()
<select id='sel' name='sel' class="selectpicker" multiple data-live-search="true" onchange="printValue(this)">
{% for desc in description %}
<option value="{{desc}}">{{desc}}</option>
{% endfor %}
</select>
<p id="mySelectedValue" style="margin-top: 10px;"></p>
<!-- In your script, call your function, which prints the data in your console-->
<script type="text/javascript">
function printValue(selectedItem){
$('#mySelectedValue').html(selectedItem.value);
}
</script>
In the method printValue()
, you print your data value using the method :). You can do anything, here, like adding to selected item to your array or Map. It is upto, we’re just printing in console for the sake of requirement 🙂
This is the SNIPPET for the REFERENCE on how onchange works in SELECT.
function printValue(selectedItem){
console.log(selectedItem.value);
}
<select class="form-control" id="your_id" onchange="printValue(this)">
<option value="Value1" selected>Value1</option>
<option value="Value2">Value2</option>
<option value="Value3">Value3</option>
</select>
Answered By – Alok
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0