简体   繁体   中英

Redirect value from checked radio button shows on

I have an unordered list with corresponding radio buttons. After choosing the radio button and pressing a submit button, I would like to take that value and use it in the redirected url. The form submits successfully, however, the value that it returns is "on" /operations/on instead of the actual value that is selected. I've tried this using regular method=POST as well as ajax to return that value but no luck.

HTML:

<form id="warehouse-selection-form" action="/" method="post">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
    <div class="tab-content mb-4" id="myTabContent">
        {% for key, values in warehouses.items() %}
            <div class="tab-pane fade" id="{{ key.lower().replace('-', '').replace('  ', ' ').replace(' ', '-') }}" role="tabpanel" aria-labelledby="{{ key.lower().replace('-', '').replace('  ', ' ').replace(' ', '-') }}-tab">
            {% for value in values %}
                <label class="btn btn-outline-secondary col-1 text-center rounded px-3 m-1" for="{{ value }}">{{ value }}</label>
                <input type="radio" class="btn-check" name="radio" id="{{ value }}" autocomplete="off">
            {% endfor %}
            </div>
        {% endfor %}
    </div>

    <button id="submit" style="display:none;" class="btn btn-primary" onclick="submitWarehouse()">Submit</button>
</form>

Flask:

@select_warehouse_bp.route("/", methods=["GET", "POST"])
def get_home():
    warehouse = request.form['radio']
    return redirect(url_for('select_warehouse_bp.get_operations', warehouse=warehouse))


@select_warehouse_bp.route("/operations/<warehouse>", methods=["GET", "POST"])
def get_buildings(warehouse):
    return render_template("base.html")

AJAX:

  • remove CSRF token if using this method and the method=post
  • I've also tried to just redirect with location.href to avoid passing back to the server, but no luck.
function submitWarehouse(){
    let warehouse = $('input[name="radio"]:checked').attr('id');

    $.ajax({
        url: `/operations/${warehouse}`,
        type: "POST",
        data: JSON.stringify({warehouse: warehouse}),
        dataType: 'json',
         success: function () {
            alert('success');
        },
        error: function () {
            alert('fail');
        }
    });
}

您没有为 input 单选标签使用 value 属性,如果您没有为 HTML 单选输入设置值,它将默认返回“on”值;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM