0

I am making a simple Flask web-app.

  • It will simply take text input.
  • The user will type in the text and click on the submit button.

I have created the textarea inside Form HTML tag for text input. And I have a Submit button created using a hyperlink tag .

How can I access the text inside the textarea when the Submit is clicked?

Note: I do not want to use the default submit option available within the form tag.

HTML for Textarea :

<form action="{{ url_for('publish') }}" method="post">
    <textarea name="text" class="form-control" rows="1" placeholder="Enter your message"></textarea>
</form>

HTML for Submit button :

<a href="{{ url_for('publish') }}" method="post"> Submit </a>

Flask code to retrieve textarea input from user :

@app.route('/publish', methods=['GET', 'POST'])
def publish():
    message = request.form['text']
    print(message)
    print('well')
    return render_template('index.html')

2 Answers2

0

Based off this question Post Method to URL from a onclick function

Assign an id to your form, then an onclick event to your link as such:

<a onclick="document.getElementById('form-id').submit();" href="{{ url_for('publish') }}" method="post"> Submit </a>

You should be able to retain your flask code as normal afterwards.

It would be easier to use the submit button inside the form element. You can always style it to your liking with CSS. If you insist on not doing do, then you will have to add a 'click' event listener on your current Submit Button that posts the textarea data to your endpoint using AJAX. Your choice of either using vanilla JS, jquery, or the like.

Then within Flask, you can access the arguments by using

from flask import request
# ... Definitions
args = request.get_json()
text = args['textarea_text'] # the key is whatever you use in your AJAX call
# ... Rest of endpoint

Here is some more information regarding that: Get the data received in a Flask request

moosearch
  • 176
  • 9
0

Is HTML for Textarea in the 'index.html'? Because I see that the route '/publish' has 'GET' method. If yes, 'index.html' should be first rendered with the 'GET' method, and the text inside the form is NOT available at this moment. You can only get the text when the 'POST' method is called.

@app.route('/publish', methods=['GET', 'POST'])
def publish():
    if request.method == 'POST':
        message = request.form['text']
        print(message, flush=True)
        return render_template('index.html')
    else:
        print('well', flush=True)
        return render_template('index.html')

By the way, you can try this to put text value into request.form['text']:

<form action="{{ url_for('publish') }}" method="post">
    <textarea name="text" id="text" class="form-control" rows="1" placeholder="Enter your message">{{ request.form['text'] }}</textarea>
</form>
Jackman Li
  • 65
  • 1
  • 8