简体   繁体   中英

How to use Flask Jinja Template generated content and JQuery Ajax functionality?

I am creating an app with Flask and JQuery which accepts input from user like this

 <form> {% for i in range(length) %} <div class="form-group has-success has-feedback"> <label for="question">Question {{ i+1 }}: {{ qlist[i] }}</label> <textarea class="form-control" rows="5" id="CAT_Custom_{{ i+1 }}" name="CAT_Custom_{{ i }}"></textarea> <span class="glyphicon glyphicon-ok form-control-feedback"></span> </div> {% endfor %} <input type="submit" name="submit" class="submit action-button" value="Submit" /> </form> 

here qlist is a list of questions like this

['What is a Network?', 'What is a Router', ...]

Before submitting the form I want to make sure that each question has an answer of at-least 100 words typed by user. So I'm trying to use a function called process which returns error or success based on the length of answer.

@app.route("/process", methods=["POST"])
def process():
    name = request.form['name']
    if len(name.split()) >= 100:
        return jsonify({'success' : name})
    return jsonify({'error': 'No data'})

Now the problem is since my form inputs are dynamically created how do I check if every individual answer is of length 100 words or above. My attempt was like this but it changes every textarea inputs not just the one with less number of words.

 $(function() { $('form').on('submit', function() { $.ajax({ data : { name : $(this).find('.form-control').val() }, type : 'POST', url : '/process' }) .done(function(data) { if(data.error) { $('.form-group').find('span').removeClass('glyphicon-ok').addClass('glyphicon-remove'); } else { $('.form-group').find('span').removeClass('glyphicon-remove').addClass('glyphicon-ok'); } }); event.preventDefault(); }); }); 

I found a solution to my problem like this

  $(function() { $('.form-group').focusout( function(event) { var target = $(this); $('.form-group').each(function() { var target = $(this); $.ajax({ data : { name : target.find('.form-control').val() }, type : 'POST', url : '/process' }) // Ajax close .done(function(data) { if(data.error) { target.find('span').removeClass('glyphicon-ok').addClass('glyphicon-remove'); } else { target.find('span').removeClass('glyphicon-remove').addClass('glyphicon-ok'); } // if close }); // done close event.preventDefault(); }); // each close }); }); 

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