In Flask, is there a way to have multiple checkboxes invoke different functions on an HTML input tag?

Issue

I have an HTML file with an input tag and two checkboxes. In a Python file I have two functions meant to act on the input tag depending on which checkbox is selected. For some reason, the function meant to calculate the gc content does not work; only the first function seems to work. How do I fix this?

HTML Code

    <form action="" method='POST' >
        <input name="sequence" type="text"><br>
        <input type="checkbox" id= "count_nuc" name="check" value="check">
        <label for="count_nuc">Count nucleotides</label>
    
        <input type="checkbox" id= "gc_content" name="check" value="check">
        <label for="gc_content">GC content</label><br>
    
        <button type="submit" value="submit">Submit</button>
    </form>
            
    {% if gc_percent %}
    <p>GC Percent: {{gc_percent}}</p>
    {% endif %}
    {% if new_dict %}
    <p>Count nucleotides: {{new_dict}}</p>
    {% endif %}

Python Code

    from flask import Flask, render_template, request
    
    app = Flask(__name__)
    
    
    @app.route("/", methods=['POST', 'GET'])
    def count_nucleotides():
        new_dict = {}
        nucleotides = ['A', 'C', 'T', 'G']
        seq = request.form.get('sequence')
        if request.method == 'POST' and 'sequence' in request.form and request.form.get("check"):
            for i in seq:
                if i not in nucleotides:
                    return 'Invalid nucleotide(s) found'
                else:
                    for j in nucleotides:
                        if j == i:
                            new_dict[i] = seq.count(i)
        return render_template('calculator.html', new_dict=new_dict)
    
    
    def gc_content():
        gc_percent = 0
        seq = request.form.get('sequence')
        if request.method == 'POST' and 'sequence' in request.form and request.form.get("check"):
            gc_percent += (round(((seq.count('G') + seq.count('C')) * 100 / len(seq)), 2))
        return render_template('calculator.html', gc_percent=gc_percent)
    
    
    app.run(debug=True)

Solution

Ok, the whole idea needs to be-revised.

First, You need to have two page, one for displaying the form, and the other one for showing the result.

so you need to create two template:

Form template (form.html)

    <form action="/submit" method='POST' >
        <input name="sequence" type="text"><br>
        <input type="checkbox" id="count_nuc" name="count_check" checked>
        <label for="count_nuc">Count nucleotides</label>
    
        <input type="checkbox" id="gc_content" name="gc_check" checked>
        <label for="gc_content">GC content</label><br>
    
        <button type="submit" value="submit">Submit</button>
    </form>

Result Template (calculator.html)

    <h1>Result</h1>

    {% if gc_percent %}
    <p>GC Percent: {{gc_percent}}</p>
    {% endif %}
    {% if new_dict %}
    <p>Count nucleotides: {{new_dict}}</p>
    {% endif %}

As you can see in the above code, I have also modified your HTML template, there were some mistakes for the name of checkbox elements that should be different from eachother.

Python Code

  from flask import Flask, render_template, request
    
    app = Flask(__name__)
    
    
    @app.route("/", methods=['GET'])
    def form():
     
        return render_template('form.html')
    
    @app.route("/submit", methods=['POST'])
    def calculator():
        new_dict = {}
        nucleotides = ['A', 'C', 'T', 'G']
        seq = request.form.get('sequence')
        
        # Getting Value of Count Check Box
        if request.form.get("count_check"):
            count_check = True
            if count_check is True:
                for i in seq:
                    if i not in nucleotides:
                        return 'Invalid nucleotide(s) found'
                    else:
                        for j in nucleotides:
                            if j == i:
                                new_dict[i] = seq.count(i)
                            
                            
        gc_percent = 0
        # Getting Value of GC Check Box

        check = False
        if request.form.get("gc_check"):
            gc_check = True
            if gc_check is True:    
                gc_percent += (round(((seq.count('G') + seq.count('C')) * 100 / len(seq)), 2))
            
        return render_template('calculator.html', gc_percent=gc_percent, new_dict=new_dict)
    
    
    app.run(debug=True)

The only thing that you need to check the code, because I’m not aware of your logic, and I’ve just tried to understand what was in your mind. If there was any ambiguous point, write a comment under this answer.

Answered By – Soroosh Khodami

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