This is the Html code:
<div class="ribbon-fav" id="fav_id">
<%- if user_signed_in? %>
<%- unless current_user.favorite_texts.exists?(id: text.id) -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite "), :id => 'fav_id_002' %>
<%- else -%>
<%= link_to image_tag("favd-hrt.png", size: "20x18", alt: "Remove from Favorites", title: " Remove from Favorites "), :id => 'fav_id_001' %>
<%- end -%>
<%- else -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite "), favorite_texts_path(text_id: text.id), method: :post, :'data-turbolinks-action' => 'replace' %>
<%- end -%>
Below is the Javascript
console.log("favorite_add_remove.js loaded");
$(document).ready(function(){
console.log("called function");
$("#fav_id a").on("click", function(e) {
e.preventDefault();
//var value = $(this).val();
console.log(e.target.id);
//console.log(value);
});
//f1();
})
I am unable to get the id or value of the link clicked. How do I get the id of the clicked element? Please help, thanks.
Please see the fiddle example. this might help you
$(document).ready(function(){
$(".test").click(function(){
var clickedId = this.id;
alert(this.id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
asda
asd
asdasd
https://jsfiddle.net/hu7r7hsu/
All you have to do is set a same class for all the anchor tags and after making it common follow the example of below code.
$(".linkClass").on("click", function() {
var clickedId = this.id;
}
Try this code:
$('#fav_id').on('click', 'a', function(){
console.log($(this).attr('id'));
});
This made it work, had to change a little bit in the html.
<div class="ribbon-fav" id="fav_id">
<%- if user_signed_in? %>
<%- unless current_user.favorite_texts.exists?(id: text.id) -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite ", :id => 'fav_id_002') %>
<%- else -%>
<%= link_to image_tag("favd-hrt.png", size: "20x18", alt: "Remove from Favorites", title: " Remove from Favorites ", :id => 'fav_id_001') %>
<%- end -%>
<%- else -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite "), favorite_texts_path(text_id: text.id), method: :post, :'data-turbolinks-action' => 'replace' %>
<%- end -%>
</div>
Removed the id from the link tag and added it to the img tag.
And the Javascript as below:
console.log("favorite_add_remove.js loaded");
$(document).ready(function(){
console.log("called function");
$("#fav_id a").on("click", function(e) {
e.preventDefault();
var imgIdVal = $('img', this).attr('id');
console.log(imgIdVal);
});
})
This gave the output as fav_id_002;
Related
I have two forms, one with uk_inputs and one with international_inputs. When one or more of the uk_inputs are filled out I want it so the international inputs in the other form are disabled.
This currently works when the first uk_input is filled out, but I can't manage to make it work but iterating over all of them with for_each.
The first code snippet is where it works with the first uk_input and the second code snippet is my attempt to iterate over all of them.
apologies if this isn't clear. thanks
$(document).ready(function() {
var uk_input = document.querySelector(".uk_input");
uk_input.onchange = function () {
international_input = document.querySelectorAll(".international_input")
international_input.forEach(function(international) {
international.disabled = uk_input.value
});
}
});
$(document).ready(function() {
var uk_input = document.querySelectorAll(".uk_input");
uk_input.for_each.onchange = function (uk) {
international_input = document.querySelectorAll(".international_input")
uk.international_input.forEach(function(international) {
international.disabled = uk_input.value
});
}
});
<%= fields.input :line_1, input_html: {class: "uk_input"} %>
<%= fields.input :line_2, input_html: {class: "uk_input"} %>
<%= fields.input :line_3, input_html: {class: "uk_input"} %>
<%= fields.input :town, input_html: {class: "uk_input"} %>
<%= fields.input :county, input_html: {class: "uk_input"} %>
<%= fields.input :postcode, input_html: {class: "uk_input"} %>
<%= fields.input :line_1, input_html: {class: "international_input"} %>
<%= fields.input :line_2, input_html: {class: "international_input"} %>
<%= fields.input :line_3, input_html: {class: "international_input"} %>
<%= fields.input :town, label: "City / Region", input_html: {class: "international_input"} %>
<%= fields.input :postcode, label: "Postcode / ZIP Code", input_html: {class: "international_input"} %>
Syntax of a for each function:
The correct syntax of the for each function in JavaScript is:
let uk_inputs = document.querySelectorAll(".uk_inputs");
uk_inputs.forEach(input=>{
input.addEventListener("click",event=>{
//Code you want to run for every uk_inputs class input
})
})
Also, as you can see detailed in the code above, to assign an event listener you must reference the DOM element you want to assign that event. This is a vanilla JavaScript solution. It's exactly the same result as it would be with jQuery.
Here is a functional fiddle. In case you want to check it out.
Adjustments to fit your question:
$(document).ready(function() {
let uk_inputs = document.querySelectorAll(".uk_inputs"),
international = document.querySelectorAll(".international");
const enabledInternational = (enabled) => {
international.forEach(input => {
if (enabled) {
input.removeAttribute("disabled");
} else {
input.setAttribute("disabled", `${enabled}`);
}
})
}
uk_inputs.forEach(input => {
input.addEventListener("change", event => {
enabledInternational(event.target.value === "");
})
})
});
The info:
I have two models: link and campaign in show.html.erb for link I have the following two forms:
<%= form_for #link, method: :delete, remote: true, id: "delete" do |f| %>
<%= f.submit :"Submit", id: "linksubmit" %>
<% end %>
<%= form_for :campaign, url: campaigns_path do |x| %>
<%= x.hidden_field :title, value: #link.title %>
<%= x.hidden_field :name, value: #link.name %>
<%= x.hidden_field :link, value: #link.link %>
<%= x.hidden_field :description, value: #link.description %>
<%= x.hidden_field :owner, value: current_user.try(:email) %>
<%= x.hidden_field :date, value: Date.today.to_s %>
<%= x.submit :Start, id: "campaignsubmit" %>
<% end %>
When I click the submit buttons on their own, they do their job, which is either destroy the link or make a new campaign I need both to submit at the same time. I tried to do that with some JQuery. This is what I have.
$('document').ready(function() {
$('button#campaignsubmit').click(function() {
$('form#delete').submit();
});
});
Doesn't work. I ran some tests, and I know the JQuery is functioning fine, just not with this function. Any help?
The issue is in this line $('document').ready(function() {. It should be $(document).ready(function() {. The binding is never getting called, so it won't bind, and thus won't work.
Edit: Side note... you can remove the tag names, since IDs are unique per page (or at least are supposed to be).
This is almost an identical question as was asked here: https://stackoverflow.com/questions/28571985/rails-remote-true-equivalent, but no one answered. I am hoping this doesn't mean that the question is impossible, though.
I have a page where a list of people can be dragged and dropped into bins. An assignment in a join table is automatically generated when they are dropped. I want the page to not re-load, though. In ruby, I would do this using remote: true, but the re-direct here happens in my javascript file. I believe everything is set up correctly, if only I could put remote: true at the end of my window.location.pathname line in the .js file.
z_game_sessions.js
app.gameSession = {
dragDrop: function () {
$('.groups-students').sortable({
tolerance:"pointer",
revert: true
});
$('.draggables').draggable({
connectToSortable: '.groups-students',
revert: 'invalid',
stop: function (e) {
var id = e.target.id;
var groupId = $(this).closest('ul').attr('id');
if (groupId) {
window.location.pathname = "game_sessions/add_player/" + groupId + "/" + id;
}
}
});
}
}
game_sessions_controller.rb
def add_player
#game_session = Group.find(params[:group_id]).game_session
GroupAssignment.assign(params[:group_id], params[:student_id], #game_session.id)
respond_to do |format|
format.js
end
end
add_player.js.erb
$("#new-group-form-container").html("<%= j(render partial: 'new_group_form', locals: {f: #game_session}) %>");
_new_group_form.html.erb
<%= f.simple_fields_for :groups do |ff| %>
<div class="mdl-cell mdl-cell--4-col mdl-shadow--4dp group-assignment-forms" id="group<%= "#{ff.object.id}" %>">
<h3>Group</h3>
Password: <%= ff.object.password %>
<%= ff.input :name, label: "Group Name", wrapper_html: { class: "mdl-textfield mdl-js-textfield mdl-textfield--floating-label" }, input_html: { class: "mdl-textfield__input" }, label_html: { class: "mdl-textfield__label" } %>
<%= ff.input :_destroy, as: :boolean, label: "Remove Group" %>
<h4>Students</h4>
<ul class="groups-students student-drag-area" id="<%= "#{ff.object.id}" %>">
<% ff.object.students.each do |student| %>
<li class="draggables" id="<%= student.id %>"><%= student.full_name %></li>
<% end %>
</ul>
</div>
<% end %>
First, it should be a POST request. Change your routes.
Second, make your controller return html and then just do an ajax request&assign that retuned html on success.
So instead of:
window.location.pathname = "game_sessions/add_player/" + groupId + "/" + id;
it should be something like:
$.ajax({
url: "game_sessions/add_player/" + groupId + "/" + id,
type: "POST",
success: function(data) {
$("#new-group-form-container").html(data)
}
});
UPDATE 8/18/12: Is there any way I can make the following question easier to answer?
I have the following code in a js.coffee file and it works for adding lined to a form. I want it to automatically add the first line on load though and don't know how to get it to to do that...
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
(If this looks familiar, it's stolen verbatim from Ryan Bates' Railscast #196 revised)
UPDATE: I tried #Baldrick's advice with the following and still no dice:
jQuery ->
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
$(document).ready '.receive-form', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
UPDATE 2: Here's some more info:
My html(the important parts):
<div class="modal-body ">
<%= #company.haves.new.warehouse_transactions.new %>
<%= form_for #company do |f| %>
<div class="form-inline receive-form">
<h4>Part Details:</h4>
<%= f.fields_for :haves do |builder| %>
<%#= render 'have_fields', f: builder %>
<% end %>
<%= link_to_add_fields "+", f, :haves, :warehouse_transactions %>
</div>
</div>
have_fields:
<fieldset>
<%= f.text_field :product_title, :class => 'input-small text_field', :placeholder => "Product Title" %>
<%= f.fields_for :warehouse_transactions do |builder| %>
<%= render 'wht_fields', :f => builder %>
<% end %>
<%= f.hidden_field :_destroy %>
<%= link_to "-", '#', class: "remove_fields" %>
</fieldset>
wht_fields:
<fielset>
<%= f.number_field :quantity, :class => 'input-small number_field', :placeholder => "Quantity" %>
<%= f.text_field :cost, :class => 'input-small text_field', :placeholder => "Cost" %>
<%= f.text_field :location, :class => 'input-small text_field', :placeholder => "Location" %>
<%= f.text_field :batch, :class => 'input-small text_field', :placeholder => "Batch" %>
<%= f.select :condition, ['Condition'] + WarehouseTransaction::CONDITIONS %>
<%= f.hidden_field :_destroy %>
<%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>
here also is the rails helper associated with the link_to_add_fields:
def link_to_add_fields(name, f, association, child_association = nil)
new_object = f.object.send(association).klass.new
id = new_object.object_id
new_object.send(child_association).new if child_association
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
I was hoping to avoid turning this question into a novel, but there it is... I hope that's enough info to get this thing working.
The code below will be executed when the page is loaded:
$(document).ready(function () {
// put here code to execute on page loading
});
If the code should be executed only on one page, put it in a javascript file that is called only by this page, or add a test in the method to execute the code only when needed.
In my view, I have the following:
<%= select("event", :event_id, events_ids_titles_hash, { :include_blank => true, :onchange => "alert_me_test()" }) %>
alert_me_test() is:
<script type="text/javascript">
function alert_me_test()
{
alert ("this is a test")
}
</script>
The dropdown is appearing fine, but when I select from it, nothing happens. I'm expecting an alert box with "this is a test" in it.
The Edit case:
When I'm doing an edit, I have the following code:
<% if #panel.event_id %>
<%= select("panel", :event_id, events_ids_titles_hash, {:selected => #panel.event_id}, { :include_blank => true}) %>
My IDE (RubyMine) does not want to accept the "onchange" as an additional argument, and putting it inside one of the :selected or :include_blank argument hashes does not produce an error, but it does not work either
What ended up working for both new and edit:
<% if #panel.event_id %>
<%= 'Event is ' + events_ids_titles_hash.key(#panel.event_id) %>
<%= select("panel", :event_id, events_ids_titles_hash, {:selected => #panel.event_id}, { :include_blank => true, :onchange => "alert_me_test()"}) %>
<% else %>
<%= 'Select Event from list' %>
<%= select("event", :event_id, events_ids_titles_hash, { :include_blank => true }, { :onchange => "alert_me_test()" }) %>
<% end %>
<%= select("event", :event_id, events_ids_titles_hash, { :include_blank => true, :onchange => "alert_me_test()" }) %>
Worked for me, but I must say that you are fighting against the current with this one. Rails follows UJS, which means your even handlers should be separate from your HTML. In this case the select would be the same minus the onclick and then the script would be
<script type="text/javascript">
$('select').change(alert_me_test);
function alert_me_test(){
...
}
</script>
You don't have to do things this way, but it makes it clearer when looking at a script where your event calls are coming from.
I believe you need to set the :onchange as an HtmlOption, which is a 4th parameter:
<%= select("event", :event_id, events_ids_titles_hash, { :include_blank => true}, {:onchange => "alert_me_test()" }) %>