Home > Net >  HTML default value fo radio button input type based on python variable
HTML default value fo radio button input type based on python variable

Time:05-11

so im making a Flask app where a user uploads a spreadsheet and then can play with the parameters of that spreadsheet on a html page. One parameter is a value which can only be 1, 2 or 3. The user is able to change this value by selecting a radio button with these options.

This all works fine but i would like the default value of the radio button to be whatever was in the initial spreadsheet that the user uploaded.

my idea was to do something like this:

main.py

@app.route('/', methods=['GET','POST'])
def params_form():

    value = 2
    value_dict = {'1': 1==value, '2': 2==value, '3': 3==value}
    
    return render_template('home/sheet.html', value_dict)

sheet.html

<div>
    <input type="radio" id="n1" name="nyears" value=1 checked={{value_dict["1"]}}>
        <label for="n1"> 1 </label>

    <input type="radio" id="n2" name="nyears" value=2 checked={{value_dict["2"]}}>
        <label for="n2"> 2 </label>

    <input type="radio" id="n3" name="nyears" value=3 checked={{value_dict["3"]}}>
        <label for="n3"> 3 </label>
</div>

But unfortunately, any use of the 'checked' attribute will check the box (in this case number 3, as it is the last to use the checked attribute). It seems that the only way to have a default checked value is to only use the checked attribute on one input line.

Any help getting this to work will be greatly appreciated Thanks in advance!

CodePudding user response:

You need to set the variable name in render_template by passing it as keyword:

@app.route('/', methods=['GET','POST'])
def params_form():

    value = 2
    value_dict = {'1': 1==value, '2': 2==value, '3': 3==value}
    
    return render_template('home/sheet.html', value_dict=value_dict)
<div>
    <input type="radio" id="n1" name="nyears" value=1  {{ 'checked' if value_dict["1"] else '' }} >
        <label for="n1"> 1 </label>

    <input type="radio" id="n2" name="nyears" value=2  {{ 'checked' if value_dict["2"] else '' }} >
        <label for="n2"> 2 </label>

    <input type="radio" id="n3" name="nyears" value=3  {{ 'checked' if value_dict["3"] else '' }} >
        <label for="n3"> 3 </label>
</div>
  • Related