Wanting to make date of birth automatically include dashes - javascript

I am wanting to edit my rails app so that the user no longer has to type slashes when they are typing in the date of birth. The app already has it configured to where if you type in the social security number it automatically includes dashes. I figure it's the same logic, and should be an easy fix. I tried putting the following code in my app, but it is not updating at all. Is there something else I need to do? I edited in the line of code, but nothing is changing.
Here's what I have:
$(document).on('ajax:success','#new-member-button', function(event, response, status,xhr){
$('.search-member-area').hide();
$('#search-member').addClass('previous-stepp');
$("#member-details").addClass('selected');
$(response).appendTo($('.add-edit-member-area'));
maskField('#member_social_security_number', '999-99-9999', '___-__-____');
maskField('#member_phone_number', '999-999-9999', '(___) ___-____');
maskField('#member_date_of_birth', '99/99/9999', '__/__/____'); //piece of code I added
});
I edited out the social_security_number to make sure that took it out, and it did. But when I add in the date of birth auto_formatter, it does nothing. Any ideas?
Edit: it appears date_of_birth is a DateTime and social_security_number is a varchar(50). Any ideas for how I would do this with a DateTime?
Edit 2: Here is my member model:
class Member < ActiveResource::Base
self.site = ServiceConfig[:vbr_service_uri]
self.element_name = 'member'
self.include_format_in_path = false
self.include_root_in_json = false
self.format = :json
validates_presence_of :first_name, :last_name, :date_of_birth, :social_security_number
validates_format_of :zip_code, with: /\A\d{5}(-\d{4})?$\z/, message: 'should be in the form 12345 or 12345-1234', :allow_blank => true
validates_format_of :phone_number, with: /\A(\d{3}-\d{3}-\d{4})?\z/, message: 'should be in the form 555-555-5555', :allow_blank => true
validates_format_of :social_security_number, with: /\A\d{3}-\d{2}-\d{4}$\z/, message: 'should be in the form 123-45-6789', :allow_blank => true
def full_name
"#{first_name} #{last_name}"
end
end

Related

Rails datatables select filter

I have an ajax datatable for my SKUs. For this I am using the ajax-datatables-rails gem. Searcing and sorting works perfectly, but now I'm trying to add a filtering function to my table and it doesn't seem to do anything. I used this example for the filter function: https://datatables.net/examples/api/multi_filter_select.html.
In the example, select boxes are drawn in the footer, but for me the footer is empty. Like the code doesn't run at all. I also don't get any errors.
I initialize my datatable in my coffeescrip file (assets/javascripts/vendor_skus.js.coffee) so I had to translate it to coffeescript. I'm not experienced with coffeescript or using ajax with rails so I'm kind of lost as to what is going wrong.
How I solved my problem:
The standard select boxes were problematic for my situation, as I am using AJAX for my table and the select boxes seemed to only work properly on client side tables. Instead of going with the standard select boxes, I decided to make my own custom filters. These are regular select boxes like so:
<%= select_tag "store-id", options_from_collection_for_select(#stores, "id", "name"), include_blank: true, class:"store-id form-control" %>
<%= select_tag "status", options_for_select([ "Open", "On Hold", "Cancelled", "Closed", "Error" ]), include_blank: true, class:"form-control", multiple:true %>
This is my coffeescript to make jQuery submit the parameters to the server and reload the table onchange:
$ ->
$('#orders-table').DataTable
processing: true
serverSide: true
retrieve: true
pageLength: 50
title: 'orders'
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]]
ajax: data: (d) ->
d.store_id = $('#store-id').val();
d.status = $('#status').val();
return
$ ->
$('#store-id').on 'change', ->
$('#orders-table').DataTable().ajax.reload()
return
$ ->
$('#status').on 'change', ->
$('#orders-table').DataTable().ajax.reload()
return
In your controller, make sure to pass the parameters along to Datatables like so:
respond_to do |format|
format.html
format.json { render json: OrderDatatable.new(view_context, { store_id: params[:store_id], status: params[:status] }) }
end
And then in your Datatable file, use the parameters to filter your results. In this case I am using a multi select for status, so when the blank value is selected, params[:status].present? results in true. That's why I added a check to see if the first item is an empty string.
def get_raw_records
# insert query here
query = Order.all
query = query.status(params[:status]) if params[:status].present? && (params[:status].count == 1 && params[:status][0] == "") == false
query = query.store(params[:store_id]) if params[:store_id].present?
query.joins(:store)
end
I ran into the same issue when implementing this. I found out that the issue was with this line:
column.search((if val then '^' + val + '$' else ''), true, false).draw()
where coffee script did not like the following bit:
, true, false
After removing it like so:
column.search(if val then '^' + val + '$' else '').draw()
everything worked fine. The caveat to this is, I am not a javascript/coffeescript guy, so what negative impact the result does is beyond me. But like you I am currently battling to get all results to appear in the selectable drop down filter. It only shows any unique values from the current page of data - which is not helpful.
FYI, to get pagination working on this, go to your datatable.rb file and uncomment the correct line toward the top that refers to the pagination you're using. I am using "will_paginate" for bootstrap, so mine looked like this:
include AjaxDatatablesRails::Extensions::WillPaginate
Hope that helps. By chance, did you find a way to show all results in the select filter?
My working code for an ajax datatable filter using the ajax-datatables-rails gem.
in the datatable view I created a table above the datatable to input the range variables, then add some javascript to reload the datatable on change:
<table>
<tbody><tr>
<td>Minimum CWD:</td>
<td><input type="text" id="minCWD" name="minCWD"></td>
</tr>
<tr>
<td>Maximum CWD:</td>
<td><input type="text" id="maxCWD" name="maxCWD"></td>
</tr>
</tbody></table>
<script>
$(document).ready(function () {
// other options
var table = $('#example').DataTable()
$("#minCWD").change(function () {
table.ajax.reload();
});
$("#maxCWD").change(function() {
table.ajax.reload();
});
});
</script>
then to add the filter variables to the ajax call (in the coffee file):
ajax: {
url: $('#example').data('source'),
beforeSend: (xhr) => xhr.setRequestHeader('Content-Type', 'application/json'),
data: (d) ->
$.extend {}, d, 'minCWD': $('#minCWD').val(),
$.extend {}, d, 'maxCWD': $('#maxCWD').val()
}
// note: the beforeSend may not be required
then add a filter in the model_datatable.rb:
def get_raw_records
#YOUR TYPICAL SELECTION...note: I'm using AREL and joining schools with pstats
#now filter by your max min variables
if params['minCWD'].present?
schools = schools.where(pstats[:cwd_percent].gteq(params['minCWD']))
end
if params['maxCWD'].present?
schools = schools.where(pstats[:cwd_percent].lteq(params['maxCWD']))
end
return schools
end
My controller looks like this:
respond_to do |format|
format.html
format.json { render json: ExampleDatatable.new(params, view_context: view_context) }
end
working example here: https://schoolsparrow.com/arizona/schools

Updating an ArrayAttribute with ReactJs

EDITED:
renamed shouldComponentUpdate to onClick
I'm using Ruby on Rails with the gem react-rails. The idea is to use a "PATCH" method to update an ArrayAttribute but using just JavaScript. To be clear, I'm still a newbie building a project while learning.
The story is, when a user checks a checkbox, it marks their post as complete. Their Post's table has a column for is_complete: :boolean, :default => false. Im using Postgres for the database.
var Foo = React.createClass({
getInitialState: function() {
return {
is_complete: this.props.data.is_complete, # shows "Empty object"
# is_complete: this.props.data[0].is_complete ..... shows "false"
# I could not use that because data[0] and data[1] etc...
}
},
onClick: function(){
var newVal = this.state.is_complete;
this.setState({
is_complete: React.addons.update(this.state.is_complete, { '$set': [ newVal ] })
})
},
render: function() {
var supports = (s) => (
<input type="checkbox" onChange={this.onClick}
/> Mark complete
);
return (
<div>
{this.props.data.map(supports)}
</div>
);
}
});
Index.html.erb:
<%= react_component('Foo', { data: #userlist }) %>
controller:
#userlist = #user.supports.as_json(:only => [:is_complete] # shortened for emample
When the checkbox is checked I get Uncaught TypeError: Cannot read property of is_complete of undefined
I'm looping through all of that user's posts (supports) and outputting the result on one page with a checkbox to mark as complete. I could achieve something similar by adding the chechbox inside of the edit page but I don't want that.
After the edit, I'm not getting the result I want. I want when checked, Array[1] and [2]'s is_complete is set to true or false.
Somehow I need to loop the getInitialState(), is that possible? I see not documentation on that.

How to implement a word counter in Rails?

I'm wanting to implement a real-time word counter in a form. So as a user types into the box, a line below the box updates with the correct number of words.
Here is the relevant form code (my views are .html.haml):
= f.semantic_fields_for :student_biography do |fb|
= fb.inputs :name => "About" do
= fb.input :short_statement, :label => 'Describe yourself! (25 words) ' , :input_html => {:id => "bio_prof_stmt" }
So below this description box, I'd like to count the number of words and display an 'out of 25' notice.
I'm assuming that this is just some javascript I need to add, but I don't know where to proceed from here.
Rails 3.2.11, Ruby 1.9.7
Thanks!
It shouldn't be too difficult, you would need a div that had its content updated on the keyup event for the input box:
This is a little bit from memory and may need some adjustment but it should get you on the right path:
= fb.input :short_statement, :label => 'Describe yourself! (25 words) ' , :input_html => {:id => "bio_prof_stmt" }, :onkeyup => "update_word_count(this);"
I think this is the right haml syntax, please correct me if not:
#word-count-container
The intended html:
<div id="word-count-container"></div>
Javascript:
<script type="text/javascript">
function update_word_count(object) {
words = object.value.match(/\S+/g).length.toString();
$('#word-count-container').innerHTML = words + " out of 25 used";
}
</script>
Alternative UJS approach (remove the onkeyup tag from the input):
<script type="text/javascript">
$('#short_statement').onkeyup(function() {
update_word_count(this);
});
function update_word_count(object) {
words = object.value.match(/\S+/g).length.toString();
$('#word-count-container').innerHTML = words + " out of 25 used";
}
</script>
This seems like something that you have to validate on the server side as well as the client side. So don't forget to do that.
validates :short_statement, length: { maximum: 25 }
If you want strict word counting you can use the Words Counted gem. Disclaimer I wrote it.

routing/asset pipeline issue - undefined javascript method

I'm getting back into Rails (it's been a few years) so I'm pretty sure I'm just missing something simple. Tho it could also be my lack of understand of how javascript works within Rails.
I think I have my view (in haml) set up correctly. I have added the javascript to a file that I made sure was included in the layout. (And the css looks right.) I'm just not getting the javascript function (a slideshow I found online) to connect to the view. I'm trying to use %body{ :onload => setUpslideShow() }
Here's my view:
%body{ :onload => setUpSlideShow() }
%script{type: 'text/javascript'}
if ( ! window.CMFmainmenu ) { CMFmainmenu = {}; }
var s = CMFmainmenu;
s.user_id = "#{#user.id.to_s}";
s.partial_mainmenu_path = "/users/" + s.user_id + "/xx/mainmenu";
s.add_new_senior = "#{UsersController::ADD_NEW_SENIOR}"
s.add_new_senior_path = "#{new_seniors_settings_path(#locale,#user,#senior)}"
#mainmenu
... (edited out to save space) ...
#slideshow.greenBorder
#slides
= image_tag '/assets/newlook/div_1_img.png', class: 'slide'
%p
Everyone loves photo albums.
Get your user ready to brag, and
populate and arrange albums by
event, special people, year or any
category you can imagine.
=link_to "Learn how.", ''
= image_tag '/assets/newlook/div_2_img.png', class: 'slide'
%p
If typing is difficult for your
loved one, remove the frustration
of a typed response. They can
respond with a voice message, or
with auto replies that you set up.
=link_to "Learn how.", ''
= image_tag '/assets/newlook/div_3_img.png', class: 'slide'
%p
Arms too short? You can specify
the minimum font size used for
your user's email.
=link_to "Learn how.", ''
#slides-controls
1
2
3
Here's my javascript:
if (! window.CMFuser) { CMFuser = {}; }
$(function() {
var s = CMFuser;
... (edited out to save space) ...
// slideshow
slidePrefix = "slide-";
slideControlPrefix = "slide-control-";
slideHighlightClass = "highlight";
slidesContainerID = "slides";
slidesControlsID = "slides-controls";
setUpSlideShow = function()
{
... lots of code that doesn't get called so I'm leaving it out to save space ...
And here's what I think the relevant line is in the layout: = javascript_include_tag "lib/modernizr-2.0.6.min", "lib/respond.min","application", "users" where "users" is the javascript file. When I comment out the %body{ :onload => setUpslideShow() }, the javascript file appears in the html source.
The full text of the error:
NoMethodError in Users#mainmenu
Showing /opt/cmf/app/views/users/mainmenu.html.haml where line #4 raised:
undefined method `setUpSlideShow' for #<#<Class:0x007fe054fa0a28>:0x007fe05594ae20>
Extracted source (around line #4):
2: - # users/mainmenu
3:
4: %body{ :onload => setUpSlideShow() }
Thanks
Shouldn't the value for :onload be a string?
%body{ :onload => 'setUpSlideShow()' }
You do want to produce this HTML after all, right?
<body onload="setUpSideShow()">

Rails: Returning a blank select option with observe_field?

I have an observe_field call in my app like this:
= observe_field "marketSelect", :update => "merchantSelect", :with => "id", :url => { :controller => "markets", :action => "get_merchants" }
That code activates the following action in my markets controller:
#merchants = #market.merchants.sort_by { |merchants| merchants.name }
That code returns a list of every merchant associated with the selected market, and populates them into another selection list.
How can I insert an empty "Select merchant..." along with the merchants?
Thank you
Hmm.. I found this at http://joshhuckabee.com/rails-observe-field-function-and
observe_field 'text_field_id',
{:function => "(value == '') ?
$('email_preview').innerHTML =
'<em>not entered yet</em>' :
$('email_preview').innerHTML =
value.replace(/\\n/g, '<br/>');",
:on => 'keyup'}
The author did this with prototype. He had added a little snippet that will replace carriage returns with HTML line breaks and also set a default value if no text is entered or the field gets cleared out.
Thanks for the suggestion. I ended up just building a straight javascript solution.

Categories