How to change Flask WTForm field value in HTML using javascript?

Issue

I have this simple hidden field in an HTML form:

<input type="hidden" id="response" name="response">{{ form.response}}</div>

and I want to change the it’s value so that I can use it using flask and WTForms later on.

I tried this:

function(token){
 document.getElementById('response').value = token
}

and the function is being called with a valid token, but no success.

Any suggestions?

Solution

The input field for a form is created as follows, where additional arguments like a label or validators are possible.

class ExampleForm(FlaskForm):
    response = HiddenField()
    submit = SubmitField()

The following code is required to request the value on the server side.

@app.route('/', methods=['GET', 'POST'])
def index():
    form = ExampleForm(request.form)
    if form.validate_on_submit():
        print(form.response.data)
    return render_template('index.html', **locals())

If you now render within the template, the attributes name and id are set automatically. The value corresponds to the identifier of the variable to which the input field was assigned. To query and set the value, you can either use a selector with the name attribute or the id of the input field.

<form method="post">
  {{ form.csrf_token }}
  {{ form.response }}
  {{ form.submit }}
</form>

<script type="text/javascript">
  (() => {
    
    const token = 'your token here';
    let responseField;
    
    // Selecting the input field based on the id attribute, 
    responseField = document.getElementById('response');
    responseField.value = token;

    // or select based on the name attribute.
    let responseField = document.querySelector('input[name="response"]');
    responseField.value = token;

  })();
</script>

Answered By – Detlef

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published