简体   繁体   English

提交时如何隐藏表格?

[英]How to hide form upon submit?

When a user submits, how can we hide the respective form? 当用户提交时,我们如何隐藏各自的表单?

<% @challenge.dates_challenged.first(@challenge.days_challenged + @challenge.missed_days).each_with_index do |date, i| %>
 <div id="show-all-notes"> # upon submit the text appears here, javascript magic
 </div>
 <div class="notes-form-background">
   DAY <%= i + 1 %>
   <%= date.strftime("%b %d, %Y") %>
   <%= form_for [@notable, @note], remote: true do |f| %>
     <%= f.text_area :notes_text %>
     <%= f.submit, class: "btn" %>
   <% end %>
 </div>
<% end %>

 <script>
   $(document).ready(function(){
     $('.btn').click(function(){
       $('form').toggle();
     });
   });
 </script>

With something like the script I have though it removes all iterations of the form, not just the one submitted. 尽管有类似脚本的内容,但它删除了表单的所有迭代,而不仅仅是提交的迭代。

Is there maybe a way to use Day <%= i + 1 %> to uniquely identify each form so that only the form that is submitted is hidden? 也许可以使用Day <%= i + 1 %>来唯一地标识每个表单,以便仅隐藏提交的表单吗?

The smallest change in your code to achieve your goal would be probably hiding the form , which is the closest ancestor to the button clicked: 为了实现目标,对代码进行的最小更改可能是隐藏form ,该form是与所单击按钮最接近的祖先

<script>
  $(document).ready(function(){
    $('.btn').click(function(){
      $(this).closest('form').hide();
    });
  });
</script>

Otherwise you could generate unique IDs for the pairs of forms and buttons, parse the ID in the button click handler, format the related form ID and find the respective form to hide by it. 否则,您可以为成对的表单和按钮生成唯一的ID,在按钮单击处理程序中解析该ID,格式化相关的表单ID并找到要隐藏的相应表单。

You can use the .closest() method to find the closest form ancestor to the .btn element: 您可以使用.closest()方法找到最接近.btn元素的form祖先:

$('.btn').click(function(){
  $(this).closest('form').toggle();
});

Demo 演示版

 $('.btn').click(function(){ $(this).closest('form').toggle(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> form1 <button class="btn">Submit</button> </form> <form> form2 <button class="btn">Submit</button> </form> 

You can try this: 您可以尝试以下方法:

$(document).ready(function(){
     $('.btn').click(function(){
       $(this).parents('form:eq(0)').toggle();
     });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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