Mischa Mischa - 1 month ago 4
jQuery Question

Rails how to insert a partial in a div table?

I'm using Rails and I've got a table made up off div's. I want users to be able to click on a table cell and have a menu (in the form of another div row) slide out underneath it. With a second click on the cell the menu should slide back up.

There should be 2 different menu's / click actions per row. I would like to add/remove a div below the clicked action. I've tried working with a table but the div's seem to work better. I just don't really know how to render the partial correctly. my code:

js:

$(document).ready(function () {
openBuySliders = [];
openSellSliders = [];

function openSlider(parent, actionType) {
$( *some partial file* ).insertAfter( parent );
}

function closeSlider() {
// remove the slider
}

$("div[buy-stocks]").click(function() {
var parent = $(event.target).parent()

if ($.inArray(cellID, openBuySliders) == -1) {
openBuySliders.push(cellID);
openSlider(parent, "buy");
}else {
var index = openBuySliders.indexOf(cellID);
openBuySliders.splice(index, 1);
closeSlider(parent);
}
})

$("div[sell-stocks]").click(function() {
var parent = $(event.target).parent()

alert(test);
if ($.inArray(cellID, openSellSliders) == -1) {
openSellSliders.push(cellID);
openSlider(parent, "sell");
}else {
var index = openSellSliders.indexOf(cellID);
openSellSliders.splice(index, 1);
closeSlider(parent);
}
})

});


my html:

<div class="rTable">
<div class="rTableRow">
<div class="rTableHead"><strong>Company</strong></div>
<div class="rTableHead"><strong>Stocks available</strong></div>
<div class="rTableHead"><strong>Stocks owned</strong></div>
</div>

<% current_game.companies.each do |company|%>
<div class="rTableRow" row-id="<%= company.id%>">
<div class="rTableCell"> <%= company.name %> </div>
<div class="rTableCell" buy-stocks="<%= game_player_view_path%>"> <%= company.stocks.size %> </div>
<div class="rTableCell" sell-stocks="<%= game_player_view_path %>"> <%= @player.stocks.where(company_id: company.id).size %> </div>
</div>
<% end %>
</div>


my controller:

def show
respond_to do |format|
format.html
format.js { render :nothing => true }
end
end


I'm trying to render it using jquery insert after but this might not be the smartest solution. I'm really struggling with the JS in the app so any help is appreciated.

Answer

I would suggest something like this:

HTML:

<table>
  <tr>
    <td> 
      <div class='click-me'> Content </div>
      <div class='menu' style='display:none'> Hidden </div>
    </td>
  </tr>
</table>

JS:

 $(document).ready(function() {
   $('.click-me').click(function(e) {
     var target = $(e.target);
     target.parent().find('.menu').toggle();
   });
 });
Comments