Get ID from modal window

时间:2016-10-20 20:13:07

标签: ruby-on-rails

I have a block of code running 3 times that will display some books and have a button to add a review. Review button fires a modal popup with form to fill to create a review. I am feeling dumb but I cant find a way to get a ID of a bookto use to create a review. Was thinkink to display it within add reiew button params but dont know how to pass it after form submit (with other button pressed withtin form itself)

1 个答案:

答案 0 :(得分:1)

每本书的模板视图

<div class="book-#{book.id}">
  ... other stuff
  <button class="review-create"> Write Review </button>
</div>

Javascript显示模态

$('.review-create').click(function(e) {
  e.preventDefault();
  // might not be parent() here but you can call parent() as many times as you want
  var bookId = $(e.currentTarget).parent().attr('class').split('-')[1];   

  // other stuff for ajax or pass bookId into modal method
  // Modal.displayForBook(bookId);
});

既然你的模态有bookId,你可以通过引用变量通过ajax提交它。希望这会有所帮助。

编辑:

由于您无法编辑当前脚本,因此可以在视图中编写新脚本。

_book.html.erb

<script type='javascript/text'>
  $('modal-button').click(function(e) {
    $('review-create').attr('id', "#{book.id}");
  });
</script

modal.html.erb

你的模态会提交ajax,不要让它做form_for助手

<script type='javascript/text'>
   $('form.create').on('submit', function(e) {
     var bookId = $(e.currentTarget).parent().attr('id');

     // ajax call here
     // on success, $(e.currentTarget).parent().attr('id', null)
   });
</script>
相关问题