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()" }) %>
Related
So I have a check_box in rails 5, and I want it to submit instantly whenever it is clicked/unclicked. It should be possible with :onclick, but I'm new to js/jquery/ajax, and haven't had any luck searching.
I have this:
<%= form_for #client, :url => url_for(:controller => 'client_admin', :action => 'clientadminpageupdate') do |f| %>
<%= f.check_box :visible, :id => "checkbox" %>
<%= f.submit 'Save' %>
What I want to this is submit the form instantly by adding an
:onclick => something-that-submits-the-form-instantly
How do I go about it?
If you just want to use it as a form submission you can use the following:
:onclick => "this.form.submit()"
How can i set a check box to true or false.. I have tried all of these combinations:
<%= check_box_tag 'prefs[can_be_email_notified]', :id => 'user_preferences_can_email'%> Email
<%= check_box_tag 'prefs[can_be_email_notified]', '', :id => 'user_preferences_can_email'%> Email
<%= check_box_tag 'prefs[can_be_email_notified]', '', :checked =>'',:id => 'user_preferences_can_email'%> Email
tried to change the checkbox with these
document.getElementById("user_preferences_can_email").checked = true;
document.getElementById("user_preferences_can_email").value = true;
document.getElementById("user_preferences_can_email").checked.value = true;
Maybe i wasnt clear...
I have a set of values that are set to buttons and want to change the checkbox's to be checked or unchecked detirmed on the value set on the the button,
ie:
function doubleClickUser(can_email, can_screen) {
document.getElementById("user_preferences_can_email").checked = can_email;
document.getElementById("user_preferences_can_screen").checked = can_screen;
}
<button class="button" onclick="doubleClickUser('true','false')"><%= user[:email] %></button>
<%= check_box_tag 'prefs[can_be_email_notified]', :id => 'user_preferences_can_email'%> Email
<%= check_box_tag 'prefs[can_be_screen_notified]', :id => 'user_preferences_can_screen' %> Screen
Set the field's value in your controller or model, then simply include the element in the standard Rails form:
# controller
#pref = Pref.new (or Pref.find(params[:id])
# view
<%= form_for #pref do |f| %>
<%= f.label :can_be_email_notified %>
<%= f.check_box :can_be_email_notified %>
<% end %>
This will reflect whatever value of can_be_email_notified #pref has.
If you want to be checked try this:
EMAIL
<%= check_box_tag "email",params[:email].to_s , {:checked => true} %>
Also if you want to assing a value you can try this:
<%= check_box_tag "email", "5", params[:email].to_s == "5", {:checked => true} %>
Figured it out you have to set the status to false first
<%= check_box_tag 'prefs[can_be_email_notified]', '', false, :id => 'user_preferences_can_email' %> Email <br>
<%= check_box_tag 'prefs[can_be_screen_notified]', '', false, :id => 'user_preferences_can_screen' %> Screen <br>
<%= check_box_tag 'prefs[can_be_sms_notified]', '', false, :id => 'user_preferences_can_sms' %> Text </div></th>
I have a Rails 3.2.13 app with some Ajax on forms and links, using the remote parameter.
The problem is that i can't find in the docs how to do the same with text fields - the
remote parameter didn't work, so i think it's not supported on input objects.
I'd like to do bind 'ajax:xxx' events (like 'ajax:success') on my text_field objects.
I this even possible with UJS? If not, what my options are?
Here's some code:
<%= form_for #post, :html => {:class => 'form-horizontal'} do |f| %>
<div class = 'control-group'>
<%= f.label :title, :html => {:class => 'control-label'} %>
<%= f.text_field :title, :placeholder => 'Title', :class => 'input-xxlarge' %>
</div>
<div class = 'control-group'>
<%= f.label :body, :html => {:class => 'control-label'} %>
<%= f.text_area :body, :placeholder => 'Your post here', :class => 'input-xxlarge',
:rows => 15 %>
</div>
<div class = 'control-group'>
<%= f.label :tags, :html => {:class => 'control-label'} %>
<%= f.text_field :tags, :placeholder => 'Tags separeted by ,', :class => 'input-xxlarge',
:value => '' %>
</div>
<%= f.submit 'Create', :class => 'btn btn-primary'%>
Thanks!
I would bind a change or blur event to the input, and then make the Ajax call manually on your javascript/coffecript file.
posts.js
$('#post_title').change(function() {
// Do your stuff, instantiate variables, etc...
$.ajax({
type: post_or_get,
url: your_url,
data: your_data,
success: function(data) {
// Handle stuff after hitting the server here
},
error: function(data) {
}
});
});
I would like to carry out a validation before saving by determining if a User has filled in a particular field, the Payment amount field below and chosen status = "Closed" before submitting the form. If he does one without the other then the form should not save
Edit page
<%= simple_form_for #invoice, :html => { :class => 'form-horizontal' } do |f| %>
<%= render "shared/error_messages", :target => #invoice %>
<%= f.association :customer, disabled: #invoice.persisted? %>
<%= f.input :due_date, as: :string, input_html: { class: "datepicker" }, disabled: #invoice.persisted? %>
<%= f.input :invoice_date, as: :string, input_html: { class: "datepicker" }, disabled: #invoice.persisted? %>
<%= f.input :payment_method, as: :select, :collection => [['Cash','Cash'],['Cheque','Cheque'],['In-House transfer','In-House transfer'],['Account Ledger','Account ledger']], :selected => ['Cash','Cash'] %>
<%= f.input :reference_no, :label => 'Payment Reference No', as: :string %>
<%= f.input :amount, as: :string %>
<%= f.input :payment_date, as: :string, input_html: {class: "datepicker"} %>
<%= f.input :status, as: :select, collection: Invoice::VALID_STATUS %>
VALID_STATUS = [ 'Draft', 'Open', 'Closed', 'Void' ] in Invoice.rb
I would like that if the user changes the Status to Closed he should have entered an amount in the form. A user should not be able to change status to closed without entering an amount
In the model (app/models/invoice_model.rb) put
validate :close_must_have_amount
Then define it (same file)
def close_must_have_amount
:status == 'closed' && :amount # May need to tweak this
end
To have the model level validations applied client side you can use
https://github.com/bcardarella/client_side_validations/
1) Javascript Form Validation is generally done by names.
function ValidateForm(){
var form = document.forms['myForm'];
if ((form['status'].value == "Closed") && !(form['amount'].value)){
alert("You gave a 'Closed' status value, but did not provide an amount, please rectify this problem!");
return(false);
} else {
return(true);
}
}
And then:
<%= simple_form_for #invoice, :onsubmit => "ValidateForm();", :html => { :class => 'form-horizontal', :name => 'myForm' } do |f| %>
<%= f.input :amount, :html => { :name => 'amount'}, as: :string %>
<%= f.input :status, as: :select, :html => { :name => 'status'}, collection: Invoice::VALID_STATUS %>
A brief walkthrough onSubmit triggers when a form is submitted, but before it is actually posted to the server.
A javascrtipt function that is trigered by an event and terminates with return(false); will immediately terminate the event, while return(true); (or pretty much anything else really) makes the event continue as planned.
Finally, be aware that relying exclusively on client side validation is a terrible idea, as a determined user could do something like:
1) Make a perfectly legitimate submission with firebug open and inspect the headers etc.
2) Craft their own HTTP request containing bogus/bad data.
3) Submit it through any one of the myriad HTTP tools.
Clientside Validation is a "nice to have".
Serverside Validation is a "must have".
If you want to do it in client side:
<script>
$(document).ready(function(){
$('#status').change(function(){
if($(this).val() == "Closed" && ($('#amount').val() == null || $('#amount') == "")){
alert("Amount must be needed when status is closed")
}
});
});
</script>
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.