Rails, Send id to URL via Javascript - javascript

I have a collection select, and I am trying to refresh the page, and pass the org_id to the URL when the user chooses from the collection select. The collection_select looks like this...
<div id="org-select">
<%= collection_select :org, :id, Org.all, :id, :name %>
</div>
In application.js I have...
$(document).ready(function(){
$("#org-select").on("change","select",function(){
val = $(this).children('option:selected').val();
window.location = '/sessions?org_id='+ val;
});
});
When the user chooses a new org from my coll_select, I am getting a page refresh. However, my URL looks like..
http://localhost:3000/sessions?org_id=2
The org_id ($this.val()) is getting set to 2 each time. It is not being updated when I choose a new org from my drop down. The page is updating, but the id is set to 2 each time.
Here is the rendered HTML...
<div id="sessions">
<div id="org-select">
<select id="org_id" name="org[id]"><option value="1">Lumbees</option>
<option value="2">Tuskarora</option></select>
</div>
The issue I am seeing now is that the page defaults to 'Lumbees' being selected in my dropdown, and even when I choose another value, the page redirects back to 'Lumbees'. Any ideas? Obviously there is a redirect somewhere, however there is nothing in app/views/sessions/index.html.erb that I can find.

what is your collection select id,i guess it org_id or write some custom id ,you are making request on change of div which is incorrect.
<div id="org-select">
<%= collection_select :org, :id, Org.all, :id, :name,{},{:id=>"org_id"} %>
</div>
$("#org_id").on("change", function(){
window.location = '/sessions?org_id='+ $(this).val()
});

Your are trying to pick an value from the div element which should not work.
If you listen on the select element insted it should work better.
$(document).ready(function(){
$("#org-select select").on("change", function(){
window.location = '/sessions?org_id='+ $(this).val()
});
});
And if it still don't work you cud also try to be more precise with the selected value like below.
$(document).ready(function(){
$("#org-select select").on("change", function(){
window.location = '/sessions?org_id='+ $(this).find(':selected').val()
});
});

try next:
UPDATED
$(document).ready(function(){
$("#org-select").on("change","select",function(){
val = $(this).children('option:selected').val();
window.location = '/sessions?org_id='+ val;
});
});

The issue with the page refresh was in the collection select...here is all the code...
app.js
$(document).ready(function(){
$("#org-select select").on("change",function(){
val = $(this).val();
window.location = '/sessions?org_id='+ val;
});
});
index.html.erb
<%= collection_select :org, :id, Org.all, :id, :name, {:selected => params[:org_id]} %>
I needed to specify an object to be selected by default.

Related

Receive Carrierwave URL through javascript

Is there a way to grab the Model.image_url through sql or javascript?
I have a select that when changed, I want the <img src=> to change dynamically.
With other situations I have done the following to change the background color of a div container:
<%= f.grouped_collection_select :color_id, #other_model, :colors, :title, :id, :title, include_blank: "Select Color" %>
<div id="div" style="background-color:<%= "#{model.color.hex}" %>;">
...
</div>
**javascript**
var colors = <%= Color.pluck(:id, :hex).to_h.to_json.html_safe %>;
document.getElementById("model_color_id").addEventListener("change", function(){
document.getElementById("div" %>").style.backgroundColor = colors[this.value];
}, false);
For getting the carrierwave imgae, I tried a similar approach:
var product_mock = <%= Item.pluck(:id, :image).to_h.to_json.html_safe %>;
document.getElementById("model_item_id").addEventListener("change", function(){
document.getElementById("item").src = product_mock[this.value];
}, false);
but this isn't grabbing the *.url' or *_url
Tried a way like this for onchange:
$('#shop_product_item_id').on('change', function(){
let item_id = $(this).val(); #tried with and without these 2 lines and with var
console.log(item_id); #tried with and without these 2 lines
var image = <%= Item.find(1).image_url %>;
document.getElementById("id").src = image;
});
There is an id:1
nothing prints to console but the following error:
Uncaught TypeError: e.unique is not a function
Is there a way to grab this from carrierwave thorugh sql or even ruby within the javascript?
You can change your code Item.pluck(:id, :image).to_h.to_json.html_safe to Item.all.map{|item| [item.id, item.image_url]}.to_h.to_json.html_safe . But as others said in comments better to get items through Ajax request not just store them in html.

Update attribute with ajax call rails

I appreciate that there may be many answers out there but if there are i cant quite interpret them to suit my needs..I am looking to update a records attribute in my model using ajax.
In my case the attribute selected: true
In my scenario i am clicking on an element and looking to update that elements record in the model
<ul class="components">
<% #component.each do |c| %>
<li id="<%= c.component_name %>" data-id="<%= c.id %>" data-remote="true"><%= c.component_name %></li>
<% end %>
</ul>
jQuery
$('#Literacy, #Numeracy').on('click', function(){
var component_name = $(this).text();
var component_id = $(this).data('id');
data_send = { id: component_id }
$.ajax({
method: 'put',
url: '/components/selected_component',
data: data_send,
success: function(data) {
console.log(data)
}
});
});
Controller
def selected_component
#component = Component.find(params[:id])
#component.update_attributes(selected: true)
end
Maybe im looking at this incorrectly but how can i get the id via the click event (stored as component_id) into my selected_component method
Im missing a few bits here but struggling with what today
At the moment I am getting an error
Missing template components/selected_component
but i dont want to render that page after successful update, I just want to stay on the same page
EDIT
to solve my issue i just had to add this to my format.js
{ render nothing: true }
A missing template error corresponds to not having a view that knows what to do when it gets a JavaScript request.
In your views/components/, just make an selected_components.js.erb file and that should clear the error you're getting.

pass selected drop down value as params in rails link_to

I have a select tag which populates list of department names, When I select a value from drop down, I need to display an edit link below (link_to) and append the selected value of dropdown as id params.(I am not using form for this single select tag since I dont need to save value in my databse). How this could be possible. Please help. I am using rails2.3
I tried like the below but it didn't work.
Select A Dept
<%=select :select_dept, :dept, #dept.map{|dept| [dept.full_name, dept.id]},{:prompt => "#{t('select_a_batch')}"} %>
<%= link_to "Display", {:controller => "user", :action => "display_value", :id => $('#select_dept').val() } ,:class => "button" %>
Gopal is on the right track.
Give the link an id so you can pick it out
<%= link_to 'Display", {:controller ...}, :class => 'button', :id => 'display_link' %>
Hide it with CSS by default
#display_link { display:none; }
#display_link.showing { display:block; }
Then in javascript, do something like
$('#select_dept').on('change', function(ev) {
var deptId = $(this).find(':selected').val();
var newPath = '/users/' + deptId + '/display_value';
$('#display_link').attr('href', newPath);
$('#display_link').addClass('showing');
});
This will not set things up on page load, but you could run the same function you've passed as the change callback on page load to set things up (assuming one of the items might be selected on load).

Rails and jQuery: How to select input from a specific form

I have a rails app with a job model, and on the index page, each job has a form. I need to be able to access the specific form everytime the submit button is selected, so I can take the input for the form and perform some jQuery validation with it.
Here is some of my index.html page.
<ul>
<% #unassigned.each do |job| %>
<li>
<div class="row new-message">
<div class="small-12 columns">
<%= form_for #message do |f| %>
<%= f.text_area :body, {placeholder: 'enter a new message...'} %>
<%= f.hidden_field :job_id, value: job.id %>
<%= f.submit 'send message', class: 'button small radius secondary message-button', "data-job-id" => job.id %>
<div id="message<%= i %>-validation-errors"> </div>
<% end %>
</div>
</div>
<li>
<% end %>
<ul>
And here is the javascript/jQuery where I try to select the input from a specific form
var messages;
messages = function() {
$('.message-button').click(function(e) {
var id = $(this).data('job-id');
messageValidation(e, id);
});
function messageValidation(e, id) {
var body = $('#message_body').val();
var div = '#message' + id + '-validation-errors';
if(body == "") {
$(div).html('');
e.preventDefault();
$(div).html('<small style="color:red"> Message body empty </small>');
}
};
};
$(document).ready(messages);
The index page will have a form for each job, and I want there to be front end validation that checks when the button is submitted, that the body field is not empty. It works fine the first time, but after going back to the index page, and trying to validate a second time var body = $('#message_body').val(); always seems to be empty, whether I put anything in the body or not. I believe it has something to do with the fact that since there is the same form for each job, there are multiple #message_body id's on the same page, and it is selecting the incorrect one. I am new to jQuery and javascript can someone please help me
You cannot have multiple elements with same id on a page. What you can do is add a class identifier to those elements.
In your case, simple set class="message_body" to your elements and select them as shown below:
$('.message-button').click(function(e) {
var id = $(this).data('job-id');
var body = $(this).parent().find('.message_body').val();
messageValidation(e, body, id);
});
To solve this problem I needed to select the child of the form and find the message_body through that.
messages = function() {
$('.new_message').submit(function(e) {
//var id = $(this).data('job-id');
var $this = $(this);
var body = $this.children('#message_body').val();
var id = $this.children('#message_job_id').val();
messageValidation(e, body, id);
});
function messageValidation(e, body, id) {
var div = '#message' + id + '-validation-errors';
if(body == "") {
$(div).html('');
e.preventDefault();
$(div).html('<small style="color:red"> Message body empty </small>');
}
};
};

How can I send an automatically generated ID for a form element to a javascript function?

I am trying to call a javascript function from my form page in a Rails 3 project. I need to send the function the ID of a particular element. Unfortunately I can't get the ID easily since it is automatically generated by a plugin.
I tried doing it this way:
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(' + the_value.id.to_s + "');"} %>
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && !#id_types_sm.include? the_value.number_type) %>
<script type="text/javascript">
setup_other_field("<%= the_value.number_type %>", ###ID WOULD GO HERE###);
</script>
<% end %>
.. But since I don't know the ID of the element, I can't call it from the function.
So now I'm trying to do it this way, by calling the function from an "onload" when the input element loads:
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && (!#id_types_sm.include? the_value.number_type) %>
<%# Call the function from the form helper only if the conditions are met %>
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(this.id);", :onload => "setup_other_field('" + the_value.number_type + "', this.id);"} %>
<% else %>
<%# Use the form helper without calling the function %>
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(this.id);"} %>
<% end %>
BUT I realize that onload does not work for this situation. Is there any workaround for this? How can I either
A) get the element ID from the field to the function in the first option, or
B) call this function from this input element whenever it loads?
... or C) an alternative way to do this?
Thanks in advance and let me know if more details would help.
If you have ID saved in the model, get it with <%= model.id %>
Exception to this rule is when you create object, and it is before it is written to database. If you go to edit or anywhere else it will be ok.
If you have it somewhere on the page :/ then you can use jQuery to get it for you.
< div id="id_of_the_element" attr_with_my_id="15" >ABC< /div >
$("#id_of_the_element").attr('attr_with_my_id')
< input id="id_of_the_element ... >< /input >
$("#id_of_the_element").value

Categories

Resources