Get attribute from model of selected option - javascript

I have an employee dropdown that lists all the employees. I want to be able to select an employee and get the address of the employee from the model so that I may display it. the following is the code of my collection_select.
<div class="form-group col-md-2 field">
<%= form.label :employee_id %>
<%= form.collection_select :employee_id, Employee.all, :id, :full_name,{:prompt=>"Select Employee"},{:id=>"emp_select",class:"form-control",:onchange=>"getEmployee();"} %>
</div>
Next is the code I am using to grab the value of the employee that was selected and it does work.
function getEmployee() {
var selectedVal=$('#emp_select option:selected').val();}
From here what do I do to get the address of the employee that was selected?

You will have to retrieve the employee's address via ajax call. Here are the steps:
Define an action in your rails app to return employee's address by json.
Make an ajax request to that action and get the info needed.
Render result into view.
For more information, take a look at this link:
https://guides.rubyonrails.org/working_with_javascript_in_rails.html
routes.rb
controller :ajax do
get 'ajax/get_employee_address/:employee_id', action: :get_employee_address, as: :get_employee_address
end
ajax_controller.rb
class AjaxController < ActionController::Base
def get_employee_address
employee = Employee.find(params[:employee_id])
render json: employee.address.to_json
rescue ActiveRecord::RecordNotFound
render json: 'Employee not found', status: 422
end
end
Your js code
function getEmployee() {
var selectedVal=$('#emp_select option:selected').val();
$.ajax({
url: '/ajax/get_employee_address/' + selectedVal,
success: function (address) {
// Render your address to view
},
error: function () {
// Handle error here or just return nothing
return null;
}
})
}
Note: This ajax endpoint will expose your employee address to outside so be sure to make authentication to prevent leaking info.

Add address to option data-attribute:
<%= form.select :employee_id,
options_for_select(Employee.all.map {
|e| [e. full_name, e.id, { 'data-address' => e.address }]
}),
{ prompt: "Select Employee" },
{ id: "emp_select", class: "form-control", onchange: "getEmployee();" } %>
On change get it with js:
function getEmployee() {
var selectedVal=$('#emp_select option:selected').data("address");}
And insert it to needed place

Related

Dynamic button values from javascript?

I have a page that does a search, using javascript, and I want to take the list of users that it comes up with, and send that as a submit to the next page. What I have, is:
.search_client_users
= form_tag admin_clients_path, method: "get" , class: "search_form" do
= label_tag 'search_term', 'Old domain name:'
= text_field_tag 'search_term', nil, autocomplete: "off", size: "50"
.main_form.client_emails
= simple_form_for(:domainNameSwap, url: { action: "update" }, html: { method: :put }) do |f|
.input-row
= f.hidden_field :users, value: #clients
.submit-row
.row
.col-xs-5
.submit
= f.submit "Update domains", id: "submit", :class => "btn btn-primary submit"
.client_list
- content_for :javascript do
= javascript_include_tag 'admin/search_client_users'
[some of the formatting may not be quite right due to cut and paste, sorry]
The admin/search_client_users creates an #clients, I'm pretty sure, at least, with:
class App.ClientUserList
constructor: ->
#incrementalSearchAttempts = 0
search: (searchTerm, completeCallback) =>
handleResponseWithOrderAwareness = (attemptNumber, response) =>
if attemptNumber >= #incrementalSearchAttempts
completeCallback(response)
#incrementalSearchAttempts++
onComplete = _.partial(handleResponseWithOrderAwareness, #incrementalSearchAttempts)
$.get('/admin/manage_clients/client_list', { search_term: searchTerm }).complete(onComplete)
class App.Views.SearchClientUsers extends Backbone.View
events:
"keyup input[name='search_term']": "search",
"click .profile_attribute": "showClientUserProfile"
initialize: =>
#clientUserList = new App.ClientUserList()
search: =>
searchTerm = $('.search_form input[name=search_term]').val()
#clientUserList.search(searchTerm, #render)
showClientUserProfile: (event) =>
window.location = $(event.currentTarget).closest('tr').data('client-path')
render: (response) =>
#$el.find('.client_list').html(response.responseText)
$ ->
new App.Views.SearchClientUsers(el: $('.search_client_users')).search()
so, I'm trying to take the list of clients, and send it to the update method in the controller. However, due to when javascript and ruby take place, it doesn't seem to be working... is there a way to do this? or do I have to figure out how to do this in Ajax?
ETA: An alternative idea is, I suppose to just turn the initial text_field into a form, so that the text field is used both for the javascript, and THEN submitted to the form, and then the update can re-do the search... My dataset is small enough that doing the search twice is not a huge problem I suppose...
But I'm not quite sure exactly how to merge the two forms...

Select2 rails does not applied to select_tag in form_for

I am working on rails 5 app. i am trying to load the data asynchronously form pgsql using jquery-select2 data is loading perfectly on search. but the problem is, i want to show the select2 tag when radio button is selected. i have two [radio buttons][1]. code for radio buttons is following
`
<%= radio_button(:new, :agent, :yes, { required: true, checked: true,
class: 'invite-rb' }) %>
<%= label_tag :new_agent_yes, 'New Agent' %>
<%= radio_button(:new, :agent, :no, { required: true, class: 'invite-rb' }) %>
<%= label_tag :new_agent_no, 'Existing Agent' %>`
I want to show the select2 box when user clicks on existing agent. but jquery-select2 is not applied to the select box.
here is my code for agent.js
$(document).on('turbolinks:load', function() {
$('.invite-rb').change(function() {
if(this.value == 'yes'){ //when i change this value to 'no' every thing works perfectly but not working with this condition
$('#agents').removeAttr('required')
$('#agent_first_name, #agent_last_name, #agent_email, #agency_code, #agent_code').attr('required', true)
$('#existing-agent-fields').addClass('hidden')
$('#new-agent-fields').removeClass('hidden')
$('#applications-div').addClass('hidden')
}
else{
$('#agent_first_name, #agent_last_name, #agent_email, #agent_agency_code, #agent_agent_code').removeAttr('required')
$('#agents').attr('required', true)
$('#existing-agent-fields').removeClass('hidden')
$('#new-agent-fields').addClass('hidden')
$('.chosen-select').select2()
$('#applications-div').addClass('hidden')
$('.chosen-select').select2({
minimumInputLength: 2,
placeholder: "Search by Agency code, agent code, name or email",
ajax: {
url: "/dashboard/agent_invitations/search_agents",
dataType: 'json',
type: 'GET',
data: function (term) {
return { q: term }
},
processResults: function (data) {
return { results: data.results }
}
}
});
}
});
i don't know whats wrong with this conditions. i don't want to change the values assigned to radio buttons because complete logic of this page depends upon them.
agent.js [1]: https://i.stack.imgur.com/AYrel.png

Stripe RailsJS, Cannot charge a customer that has no active card

I keep getting the "Cannot charge a user that has no active card" error when trying to bill a test user.
The app works so that a user gets charged $10 on sign up after they input their CC credentials.
I know the customers are being created but the charges aren't being sent
Here is the Stripe error
My credit_card_form.js file which is what collects the credit card info and sends it to stripe without it hitting my database.
$(document).ready(function(){
var show_error, stripeResponseHandler, submitHandler;
submitHandler = function (event) {
var $form = $(event.target);
$form.find("input[type=submit]").prop("disabled", true);
//If Stripe was initialized correctly this will create a token using the credit card info
if(Stripe){
Stripe.card.createToken($form, stripeResponseHandler);
show_error("CC token generated")
} else {
show_error("Failed to load credit card processing functionality. Please reload this page in your browser.")
}
return false;
};
// calling the SUBMIT
$(".cc_form").on('submit', submitHandler);
// RESPONSE HANDLER
stripeResponseHandler = function (status, response) {
var token, $form;
$form = $('.cc_form');
if (response.error) {
console.log(response.error.message);
show_error(response.error.message);
$form.find("input[type=submit]").prop("disabled", false);
} else {
token = response.id;
$form.append($("<input type=\"hidden\" name=\"payment[token]\" />").val(token));
$("[data-stripe=number]").remove();
$("[data-stripe=cvv]").remove();
$("[data-stripe=exp-year]").remove();
$("[data-stripe=exp-month]").remove();
$("[data-stripe=label]").remove();
$form.get(0).submit();
}
return false;
};
//ERROR HANDLING
show_error = function (message) {
if($("#flash-messages").size() < 1){
$('div.container.main div:first').prepend("<div id='flash-messages'></div>")
}
$("#flash-messages").html('<div class="alert alert-warning"><a class="close" data-dismiss="alert">×</a><div id="flash_alert">' + message + '</div></div>');
$('.alert').delay(5000).fadeOut(3000);
return false;
};
});
And payment.rb
class Payment < ApplicationRecord
attr_accessor :card_number, :card_cvv, :card_expires_month, :card_expires_year
belongs_to :user
def self.month_options
Date::MONTHNAMES.compact.each_with_index.map{|name,i| ["#{i+1} - #{name}", i+1]}
end
def self.year_options
(Date.today.year..(Date.today.year+10)).to_a
end
def process_payment
customer = Stripe::Customer.create email:email, card:token
Stripe::Charge.create customer:customer.id, amount: 1000, description: "Premium", currency: "usd"
end
end
And a snippet of the devise registrations new.html.erb which is where the user will be charged from
<div class="col-md-3">
<%=p .select :card_expires_month, options_for_select(Payment.month_options), {include_blank: "Month"}, "data-stripe"=>"exp-month", class: "form-control", required: true%>
</div>
<div class="col-md-3">
<%=p .select :card_expires_year, options_for_select(Payment.year_options.push), {include_blank: "Year"}, class: "form-control", data: {stripe: "exp-year"}, required: true%>
</div>
I know that the customers are being created but I have no clue why my customers aren't paying when I use the test credit card numbers. No answers on stack overflow have helped me as of yet.
Jack and I had a chat and discovered that Stripe.js wasn't loading, so the token wasn't being sent in the request.
The issue was <%= javascript_include_tag 'https://js/stripe.com/v2' %> being a mistyped js link in application.html.erb
The fix was making it <%= javascript_include_tag 'https://js.stripe.com/v2/' %>

Changing from observe_field to JQuery in Rails 3

Prior to Rails 3, I used this code to observe a field dynamically and pass the data in that field to a controller:
<%= observe_field :transaction_borrower_netid,
:url => { :controller => :live_validations, :action => :validate_borrower_netid },
:frequency => 0.5,
:update => :borrower_netid_message,
:with => "borrower_netid" %>
I'm trying to update that code to work with Jquery and Rails 3, but I can't get it to work. I updated my routes.rb to include
match "/live_validations/validate_borrower_netid" => "live_validations#validate_borrower_netid", :as => "validate_borrower"
and I'm trying to observe the field and make the necessary calls with:
jQuery(function($) {
// when the #transaction_borrower_netid field changes
$("#transaction_borrower_netid").change(function() {
// make a POST call and update the borrower_netid_message with borrower_netid
$.post(<%= validate_borrower_path %>, this.value, function(html) {
$("#borrower_netid_message").html(html);
});
});
})
but it's not working. My Javascript and Jquery skills are severely lacking, so any help anyone could provide would be much appreciated. Thanks!
You need to wrap your <%= validate_borrower_path %> in quotes:
$.post("<%= validate_borrower_path %>", this.value, function(html) {
I ended up using the following:
$('#transaction_borrower_netid').live('change', function() {
// when the #transaction_borrower_netid field changes
// make a POST call and replace the content
var netID = $('#transaction_borrower_netid').val();
$.post("/live_validations/validate_borrower_netid", { borrower_netid: $('#transaction_borrower_netid').val() }, function(html) {
$("#borrower_netid_message").html(html);
});
})

Rails, javascript and updating forms

I have a form that allows the user to choose a country. Depending on which country is selected, I need to change the State/Province drop-down to include either a list of states or a list of provinces. I was going about this using the observe_field tag, but that was depreciated in rails 3...
So.., how should one go about this now? I am using select_tag to populate the drop-downs, and the arrays used in the options_for_select are all stored server-side and made accessible in the controller action, so I can't access them from javascript..
Using the Carmen gem: https://github.com/jim/carmen.
I did the following some times ago (AJAX).
HTML:
<p>
<label>Country <span>*</span></label>
<%= profile_form.select(:country,Carmen.countries, {:include_blank => 'Select a Country'}, :id => "profile_country") %>
</p>
<p>
<label>State <span>*</span></label>
<%= profile_form.select(:state, "" , {:include_blank => 'Select a Country first'}, :id => "profile_state") %>
</p>
Controller:
def states
begin
render :json => Carmen::states(CGI::unescape(params[:country]))
rescue
render :json => {"content" => "None"}.to_json
end
end
Javascript with jQuery:
$('#profile_country').change(function() {
if ($(this).val() == '')
{
$('#profile_state').empty();
$('#profile_state').append( $('<option>No state provided for your country</option>'));
}
else {
$.ajax({
type: "GET",
url: "/remote/get_states/" + encodeURIComponent($(this).attr('value')),
success: function(data){
if (data.content == 'None')
{
$('#profile_state').empty();
$('#profile_state').append( $('<option>No state provided for your country</option>'));
}
//handle the case where no state related to country selected
else
{
$('#profile_state').empty();
$('#profile_state').append( $('<option>Select your State</option>'));
jQuery.each(data,function(i, v) {
$('#profile_state').append( $('<option value="'+ data[i][1] +'">'+data[i][0] +'</option>'));
});
}
}
});
}
});

Categories

Resources