Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding onclick javascript function to template blocks Python Flask routing

I have an HTML form and a submit button attached to a JavaScript function that greys out the button on click.

<form action="/feedback" method="POST">
<fieldset class="rating">
    <input type="radio" id="star5" name="rating" value="5" /><label class = "full" for="star5" title="Awesome - 5 stars"></label>
    <!-- there are more fields but I omit them for brevity -->
</fieldset>
<input type="submit" value="Submit" id="feedback-submit" onclick="thanks()">
</form>

<script>
function thanks(){
    var button = document.getElementById("feedback-submit")
    button.value = "Thanks!";
    button.disabled = true;
}
</script>

And the /feedback endpoint is routed to a Flask function that reads the value from the fieldset.

@app.route('/feedback', methods=["POST", "GET"]
def feedback():
    if request.method == "POST":
        logging.info(form['rating'])
        return "Thanks for submitting"

It seems like having the onclick tag in my submit button makes it so that the feedback() function is never reached. When I remove the onclick feedback() executes normally.

I am just curious as to why this is and if there is any way to still get similar functionality.

Thanks!

like image 335
Carlos G. Oliver Avatar asked Sep 19 '25 04:09

Carlos G. Oliver


1 Answers

You can read about why onclick on submit button does not work together Submit and onclick not working together

Here is working solution for you.

In your form just assigned id=someForm

<form id="someForm" action="/feedback" method="POST">
<fieldset class="rating">
    <input type="radio" id="star5" name="rating" value="5" /><label class = "full" for="star5" title="Awesome - 5 stars"></label>
    <!-- there are more fields but I omit them for brevity -->
</fieldset>
<input type="submit" value="Submit" id="feedback-submit" onclick="thanks()">
</form>

In your script:

function thanks(){
    var button = document.getElementById("feedback-submit");
    button.value = "Thanks!";
    button.disabled = true;
    var form = document.getElementById("someForm");
    form.submit();
}
like image 63
BeeBee8 Avatar answered Sep 20 '25 17:09

BeeBee8