Jquery: How to apply a function to many ids - javascript

I have a page of divs that I want only to appear if the proper link is clicked. Each div has an id corresponding to tag id to be displayed. For example for my tag with id 1, the link to click has an id="tag1s" and the div with the object information has an id="tag1". Here is my javascript that I want to work in the html:
<script>
$(document).ready(function() {
$('tag'+id+'s').click(function(event) {
event.preventDefault();
$('#tag'+id).toggle();
});
});
</script>
Currently this works if I put in the specific ids. But I want this to work for every id in my #tags. Here is the html:
<h1>Tags</h1>
<div class="home unlimited">
<div class="flex-container top-row">
<div class="tag-buttons">
<% #tags.each do |tag| %>
<%= link_to "#", id:"tag#{tag.id}s", class:"tag-btn" do%>
<div class="tag-button">
<%= tag.name %>
</div>
<% end %>
<% end %>
<div class="tag-button">
<%= render :partial => 'layouts/create_tags', :locals => { :tag => Tag.new} %>
</div>
</div>
<div class="tag-display">
<% #tags.each do |tag| %>
<div id=<%="tag#{tag.id}"-%> class="individual-tags">
<%= render :partial => "show_display", :locals => { :courses => #tag_relation_c[tag], :lessons => #tag_relation_l[tag], :tag => tag } %>
</div>
<% end %>
</div>
</div>
</div>
How can make it so I can have the function work for every tag_id?

It's close. Just make the selector on a class for the button press and read the id off an attribute of the button, something like this...
<script>
$(document).ready(function() {
$('tag-btn').click(function(event) {
var id = $(this).data('tag-id');
event.preventDefault();
$('#tag'+id).toggle();
});
});
</script>
Then change your markup accordingly...
<h1>Tags</h1>
<div class="home unlimited">
<div class="flex-container top-row">
<div class="tag-buttons">
<% #tags.each do |tag| %>
# The line below is all that changes
<%= link_to "#", class:"tag-btn", data: { tag_id: tag.id % } do%>
<div class="tag-button">
<%= tag.name %>
</div>
<% end %>
<% end %>
<div class="tag-button">
<%= render :partial => 'layouts/create_tags', :locals => { :tag => Tag.new} %>
</div>
</div>
<div class="tag-display">
<% #tags.each do |tag| %>
<div id=<%="tag#{tag.id}"-%> class="individual-tags">
<%= render :partial => "show_display", :locals => { :courses => #tag_relation_c[tag], :lessons => #tag_relation_l[tag], :tag => tag } %>
</div>
<% end %>
</div>
</div>
</div>

Related

Replacing text with Jquery works with class but not id

So for the view page I've tried <div id= <%= dom_id(Video.find(x.id)) %>> <%= x.get_upvotes.size %> </div>
For the upvote.js.erb page I've tried Rails.$('#<%=dom_id(Video.find(#video.id))%>').innerHTML = ("<%= j (render partial: 'book', locals: { book: #video }) %>")
On the JS page console.log('#<%=dom_id(Video.find(#video.id))%>')
gives me an output of #video_12
And on the view page <% puts dom_id(Video.find(x.id)) %> gives me an output of video_12
So I'm not sure where I'm going wrong. Any help is much appreciated.
Routes
resources :videos do#, only: [:index, :show] do
member do
put "upvote", to: "videos#upvote"
put "downvote", to: "videos#downvote"
end
end
_book.html.erb
<p> Title: <%= book.get_upvotes.size %> </p>
upvote.js.erb
Rails.$('.random-book')[1].innerHTML = ("<%= j (render partial: 'book', locals: { book: #video }) %>")
console.log('#<%=dom_id(Video.find(#video.id))%>')
console.log(Rails.$('.random-book')[0])
def upvote
def upvote
#video = Video.find(params[:id])
#ip = request.remote_ip
#was_it_upvoted = Ipaddresstracker.find_by(ipaddress: #ip, videoid: #video.id)
if #was_it_upvoted
#video.downvote_by User.first
#was_it_upvoted.delete
else
Ipaddresstracker.create(:ipaddress => #ip, :videoid => #video.id)
#video.vote_by voter: User.first, :duplicate => true
end
end
_index.html.erb
<div class="container">
<% #videos.each do |x| %>
<p> <div class="child">
<video controls width="310" height="230" src="<%= x.file %>"></video>
<p> <%= x.title %> </p>
<div>
<%= link_to upvote_video_path(x), method: :put, remote: :true, class: "btn btn-default btn-sm" do %>
<span class="glyphicon glyphicon-chevron-up"></span>
Upvote
<div class="random-book" id= <%= dom_id(Video.find(x.id)) %> > <%= x.get_upvotes.size %> </div>
<% end %>
<div>
<br><br>
<% if user_signed_in? %>
<p> Contributor: <%= x.contributor %> </p>
<p> Email: <%= x.email %> </p>
<p> Phone: <%= x.phone %> </p>
<p> <%= link_to 'Destroy', x, method: :delete, data: { confirm: 'Are you sure?' } %> </p>
<% end %>
</div>
</div>
</div> </p>
<% end %>
</div>
i think you need to add quotes
instead of
<div class="random-book" id= <%= dom_id(Video.find(x.id)) %> ></div>
do:
<div class="random-book" id="<%= dom_id(Video.find(x.id)) %>" ></div>

Form select option to change what gets rendered

Ruby on Rails 4 form with a drop down selection. If Multiple Choice is selected I want to render a page. If True/False is selected I want to render a different page.
I do not know why this isn't working, My javascript knowledge is bad:
<h1>New question</h1>
<%= form_for(#question) do |f| %>
<%= render 'shared/error_questions' %>
<%= render 'form', f: f %>
<%= f.fields_for :answers do |builder| %>
<div id="mcanswers" style="display:none">
<h1>Answers</h1>
<%= render 'four_answers', :f => builder %>
<%= f.submit "Create Question", class: "btn btn-lg btn-primary" %>
</div>
<div id="tfanswers" style="display:none">
<h1>Answers</h1>
<%= render 'tf_answers', :f => builder %>
<%= f.submit "Create Question", class: "btn btn-lg btn-primary" %>
</div>
<% end %>
<% end %>
<hr />
<%= link_to 'Back', questions_path %>
<script>
function checkType() {
if ($('#question_question_type').val('MC'))
{
$('#mcanswers').css('display', 'block');
}
else if ($('#question_question_type').val('TF'))
{
$('#tfanswers').css('display', 'block');
}
}
$(document).ready(function() {
$('select#question_question_type').on('change', function() {
checkType();
});
});
</script>
Everything is rendered from the beginning. The div is just hiding it. I had to use controller logic to decide when to render.

Call jQuery function from Rails link_to

I have a ruby loop that creates a list of comments..
I wonder if I can attach jQuery function to Rails link_to helper in this case?
<% #video.phrases.each do |phrase| %>
<div class = "span4" id ="comment" ><%= phrase.content %></div><a id ="ff" ><%= image_tag("ff.png", :size=> "32x32" )%></a>
<% end %>
I am hoping for something like
<% #video.phrases.each do |phrase| %>
<div class = "span4" id ="comment" ><%= phrase.content %></div><%= link_to (image_tag("ff.png", :size=> "32x32" ), html => {<script>$("#video_div").html('CONTENTS OF HTML');</script>} :remote => true %>
<% end %>
I know it won't work, but I wonder is there an easy way to achieve this kind of functionality?
Thanks!
You can do this two ways.
The first is the add an html attribute on the link_to:
<% #video.phrases.each do |phrase| %>
<div class = "span4" id ="comment" >
<%= phrase.content %>
</div>
<%= link_to (image_tag("ff.png", :size=> "32x32" ), html => {:onclick => "$('#video_div').html('CONTENTS OF HTML');"} :remote => true %>
<% end %>
The second is to separate the Javascript from Ruby:
<% #video.phrases.each do |phrase| %>
<div class = "span4" id ="comment" >
<%= phrase.content %>
</div>
<%= link_to (image_tag("ff.png", :size=> "32x32" ) :remote => true %>
<% end %>
<script type="text/javascript">
$('a').click(function(){
$("#video_div").html('CONTENTS OF HTML');
);
</script>
If you want the contents of the link tag, substitute 'CONTENTS OF HTML' for $(this).html()
Also I actually found out about Rails link_to_function helper and was able to achieve the desired behavior with:
<% #video.phrases.each do |phrase| %>
<div class = "span4" id ="comment" ><%= phrase.content %></div><a id ="ff">
<%= link_to_function image_tag("ff.png", :size=> "32x32" ), "use_comment('#{phrase.comment}')"%>
</a>
You might want to use event delegation, since it seems like you'll be creating a large number of comments.
So, borrowing from grant something like:
<% #video.phrases.each do |phrase| %>
<div class = "span4" id ="comment" >
<%= phrase.content %>
</div>
<%= link_to (image_tag("ff.png", :size=> "32x32" ) :remote => true %>
<% end %>
<script type="text/javascript">
$("#comment-wrapper-name-here").on("click", "a", function() {
$("#video_div").html('CONTENTS OF HTML');
);
</script>

How do I apply function to just the class a jquery ajax submission was done from?

Here is the code I'm currently using:
$.ajax({
success: function(){
$('.post_container').append('test <br />');
}
});
<% sleep 1 %>
It is similar to the code I used for my single main micropost form but with this there are several comments that use the same class and so test is being applied to all post_containers rather than the one the post was just made to. "test" text will eventually be replaced with the div that holds the actual comments users post.
Normally I would use "this" but that won't work here.
HTML:
<div class="post_content">
<div class="post_container">
<div class="userNameFontStyle">
<%= link_to current_users_username.capitalize, current_users_username %> -
<div class="post_time">
<%= time_ago_in_words(m.created_at) %> ago.
</div>
</div>
<%= simple_format h(m.content) %>
</div>
<% if m.comments.any? %>
<% comments(m.id).each do |comment| %>
<div class="comment_container">
<%= link_to image_tag(default_photo_for_commenter(comment), :class => "commenter_photo"), commenter(comment.user_id).username %>
<div class="commenter_content">
<div class="userNameFontStyle">
<%= link_to commenter(comment.user_id).username.capitalize, commenter(comment.user_id).username %> - <%= simple_format h(comment.content) %>
</div>
</div>
<div class="comment_post_time">
<%= time_ago_in_words(comment.created_at) %> ago.
</div>
</div>
<% end %>
<% end %>
<% if logged_in? %>
<%= form_for #comment, :remote => true do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :micropost_id, :value => m.id %>
<%= f.text_area :content, :placeholder => 'Post a comment...', :class => "comment_box", :rows => 0, :columns => 0 %>
<div class="commentButtons">
<%= f.submit 'Post it', :class => "commentButton" %>
<div class="cancelButton">
Cancel
</div>
</div>
<% end %>
<% end %>
</div>
</div>
How would I deal with this?
Kind regards
NEW:
$(function() {
$('.post-form').submit(function(){
var $post_content = $(this).find('.post_content');
$.ajax({
url: this.attributes['action'],
data: $(this).serialize(),
success: function() {
$post_content.append('test <br />');
}
})
return false; //this will stop the form from really submitting.
});
});
This should do what you're looking for. Simply include this javascript anywhere.
OLD:
$('form').submit(function(){
$.ajax({
url: this.attributes['action'],
data: $(this).serialize(),
//the below line might need to be adapted.
var post_content = $(this).find('.post_content');
success: function() {
$(post_content).append('test <br />');
}
})
this assumes that there is only one form on the page. However, for the code to completely work, I need to know how to differentiate which .post_content is the "submitted" post_content. How do you programatically determine that? Is there a different button for each post_content? Or are there different forms around each post_content div? Whichever way it is, you'll have to include that somehow into the js code.
This is how I had to do it in the end.
.new_comment is my form id
$('.new_comment').on('ajax:success', function(){
$(this).parent('.post_content').find('.comment_container:last').after("<BR />TEST <BR />");
});
<% sleep 1 %>
The only issue now is identifying the actual comment_container for the post just made.

Rails help to preview text area

I am trying to create a preview for my text area:
I have tried this:
My controller:
def preview
post = Post.new(params[:post])
render :text => post.body_html
end
def new
#post = Post.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #post }
end
end
And my form:
<%= form_for(#post) do |f| %>
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :titel %><br />
<%= f.text_field :titel %>
</div>
<div class="field">
<%= f.label :body_html %><br />
<%= f.text_area :body_html %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
How should I make a preview in my form of the body_html text area?
I want to have a preview when a type something in the body_html text_area it gets previewed instant.
Is the user entering HTML that you want rendered in the preview? Or just the text as is?
I guess either way, add a div for the preview:
<div id='preview'></div>
and then using jQuery:
var $html = $('#body_html');
$html.bind('change keyup',function(){
$('#preview').html($html.val());
});

Categories

Resources