【问题标题】:Required radio buttons HTML / Flask必需的单选按钮 HTML / Flask
【发布时间】:2018-12-28 12:20:51
【问题描述】:

我正在使用 Flask 和 HTML5 制作情绪分析 UI。在主页 html 页面(使用 render_template 从 Flask 链接)上,我有单选按钮。我有一条自定义消息和一个“必需”设置,因此如果未选择单选按钮并且用户尝试点击“提交”,则会显示一条消息并且用户无法提交。 问题是,如果未选择单选按钮,则消息不会消失,并且即使用户选择了按钮,也不允许用户提交答案。必须刷新页面才能避免这种情况。

如果我删除整个“onvalid”部分并只留下“required”部分,它工作得很好,但是我丢失了自定义消息并且只有一个默认消息。如果有人能帮助我理解为什么会发生这种情况以及如何解决它,我将不胜感激。

提前非常感谢。这是有问题的代码部分(特别是第 4 行):

<form method="post"><center class='sansserif'>
<table>
<tr>
<td><input type="radio" name="sentiment" value=1 oninvalid="this.setCustomValidity('Please select a rating before continuing.')" required="required"> Very negative<br>
</td>
</tr>
<tr>
<td><input type="radio" name="sentiment" value=2> Negative<br>
</td>
</tr>
<tr>
<td><input type="radio" name="sentiment" value=3> Neutral<br></td>
</tr>
<tr>
<td><input type="radio" name="sentiment" value=4> Positive<br></td>
</tr>
<tr>
<td><input type="radio" name="sentiment" value=5> Very Positive 
</center></td>
</tr>
<tr><td><br></td></tr>
<tr>
<td><center><input type="checkbox" name="English" value= 'checked'> <em> This sentence is in English</em></center><br></td>
</tr>
<tr>
<td><input class="button" type="submit" value="Submit"/></td>
</tr>
</table>
<br>
</form>

【问题讨论】:

  • 你在使用 Flask-WTF 吗?

标签: python html flask


【解决方案1】:

您可以使用jquery 来 1. 如果单选按钮未选中,则显示一条消息 2. 如果用户单击单选按钮,则原始消息将被删除

<html>
<table>
 <tr>
  <td><input type="radio" name="sentiment" value=1> Very negative<br>
 </td>
 </tr>
 <tr>
 <td><input type="radio" name="sentiment" value=2> Negative<br>
 </td>
 </tr>
 <tr>
 <td><input type="radio" name="sentiment" value=3> Neutral<br></td>
 </tr>
 <tr>
 <td><input type="radio" name="sentiment" value=4> Positive<br></td>
 </tr>
<tr>
 <td><input type="radio" name="sentiment" value=5> Very Positive 
</center></td>
</tr>
<tr><td><br></td></tr>
<tr>
<td><center><input type="checkbox" name="English" value= 'checked'> <em> This 
 sentence is in English</em></center><br></td>
</tr>
<tr>
<td><button class='get_input'>Sumit</button></td>
</tr>
<div class='user_warning_message'></div>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
   $('.get_input').click(function() {
   if ($('input[name=sentiment]:checked').length === 0) {
    $('.user_warning_message').html('<div style="width:100px;height:50px;background-color:red">checkbox not selected</div>');
    }
  });
  $("input[name='sentiment']").change(function(){
    $('.user_warning_message').html('');
  });
});
 </script>
</html>


如果在未选择任何单选按钮的情况下单击按钮,此当前解决方案将显示错误消息,如果再次选择单选按钮之一,则会清除该消息。

【讨论】:

  • 嗨。感谢您的回复,但我只使用 Python,而不是 Jquery。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 2014-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多