简体   繁体   中英

Pass python flask object into jQuery or JavaScript

I have following jQuery which modifies my html code:

$('input[name="date-format"]').change(function () {
    if ($(this).val() == '0') {
        $(".date-range").html(`<div class="eu-input">
                                    <label>Date from</label><input name="eu-date-from">
                                    <label>Date to</label><input name="eu-date-to">
                                </div>`);
    }
    else if ($(this).val() == '1') {
        $(".date-range").html(`<div class="us-input">
                                    <label>Date from</label><input name="us-date-from">
                                    <label>Date to</label><input name="us-date-to">
                                </div>`);
    }
});

On the backend however, I have python flask and I am trying to pass flask-wtf form within the modified html. Plain html and python code on the backend would look like this:

<div class="eu-input">
    <label>Date from</label>
    {{ form.eu_dates() }}
    <label>Date to</label>
    {{ form.eu_dates() }}
</div>


@app.route('/', methods=["GET", "POST"])
def home():
    form = MyForm()
    return render_template('index.html', form=form)

I am struggling to pass the python object into the JavaScript code and then include within the new html content. Thanks for your help.

I'm not sure what are you trying to accomplish, my guess is that you want to change the date format based on user choice between:

  1. DD.MM.YYYY
  2. MM.DD.YYYY

And you have two form field, one for the US format and the other for the EU format.

If this the case you can render the two fields and wrap them in a div as follows:

    <div id="us-date-container">
        {{ form.us_dates() }}
    </div>

    <div id="eu-date-container">
        {{ form.eu_dates() }}
    </div>

and toggle their visibility using jQuery or JavaScript:

$('input[name="date-format"]').change(function () {
    if ($(this).val() == '0') { // show EU format
        $("#eu-date-container").show();
        $("#us-date-container").hide();
    }
    else if ($(this).val() == '1') { // show US format
        $("#eu-date-container")[0].hide();
        $("#us-date-container")[0].show();
    }
});

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