我能在Flask中使用html中的单选按钮文本吗



我正在开发一个简单的web应用程序,该应用程序允许用户对电影进行评分和评论,并将它们存储在数据库中以便稍后查看。用户输入一部电影进行评分,如果该电影标题由多部电影共享,则会提示用户指定他们想要的电影。我已经选择在我的html文件中使用单选按钮,但我不知道如何获得所选按钮的文本并在Flask中使用它。该应用程序取所选胶片的名称,并将该名称打印在不同的html文件的顶部,但无论我做什么,它总是打印";无";而不是所选的标题。

我找到了这个答案:在JQuery中获取所选单选按钮的文本,这让我尝试了

var confirmed = $("input[name='confirmation']:checked").parent('label').text();

在我的html脚本中,以获取选中按钮的文本。但当我试图在弗拉斯克提出这个要求时,它并不起作用。

confirm.html:

<div id="id02" class="modal" data-backdrop="false">
<form class="modal-content animate" action="/confirm" method="post">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal">&times;</span>
<div class="container">
<h1>Please Specify Which Title to Rate:</h1>
{% for movie in multi %}
<label class="container">{{movie["title"]}} ({{movie["year"]}})
<input type="radio" id={{movie["year"]}} name="confirmation">
<span class="checkmark"></span>
</label>
{% endfor %}
<button type="submit">Rate</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</form>
</div>
<script>
// Get the modal when page is loaded 
$(window).on('load',function(){
$('#id02').modal('show');
});

var modal = document.getElementById('id02');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
};

// variable storing the name of the film selected   
var confirmed = $("input[name='confirmation']:checked").parent('label').text();

</script>

application.py:

@app.route("/confirm", methods=["GET", "POST"])
def confirm():
if request.method == "POST":

full = request.form.get("confirmed")

session["title"] = full # add movie title to session in order to use in rate function
return render_template("rate.html", full=full)
else:

return render_template("confirm.html")

我也尝试过为按钮分配一个id,如果它被选中,希望从id中获得文本,但当我尝试时,我只得到了";无";也

{% for movie in multi %}
<label class="container">{{movie["title"]}} ({{movie["year"]}})
<input type="radio" name="confirmation">
{% if checked=="checked" %}
<input type="hidden" id="confirmed" value="({{movie["year"]}})">
{% endif %}
<span class="checkmark"></span>
</label>
{% endfor %}

我对编程很陌生,这是我第一次尝试制作web应用程序,所以非常感谢您在这方面的帮助!

当flask给您一个单选按钮值时。它给你的是值属性,而不是单选按钮文本,所以你只需要把值属性放在单选按钮中

最新更新