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

Time:04-26

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?

CodePudding user response:

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.
    responseField = document.querySelector('input[name="response"]');
    responseField.value = token;

  })();
</script>
  • Related