Checkbox change event only fire after reloading page - javascript

 I'm writing an app using Ruby on Rails, there I have a form where if a checkbox is checked it displays a certain <div> and if it isn't I add style="display:none:" through rails. Via Coffeescript and JQuery, I also toggle the same <div> on change.
Coffeescript:
jQuery ->
$(document).ready ->
$("#hasUser").change ->
$("#userPart").toggle();
return
return
return
HTML:
<div class="form-group">
<%= contato_form.label :hasUser, :class => 'inline-checkbox' do %>
Possui usuário <%= contato_form.check_box :hasUser, :id => 'hasUser' %>
<% end %>
</div>
</div><!-- Closing from uncopied code -->
<div id="userPart" class="findMe" <% if #contato.usuario.id.blank? %> style="display:none;" <% end %>>
<h2> Usuário: </h2>
<div class="container">
<%= contato_form.fields_for :usuario do |usuario_form| %>
<%= render partial: 'usuarios/campos_usuario', locals: {form: usuario_form} %>
<% end %>
</div>
</div>
The issue here is that it all runs well when I use the form to Create, but on Edit the Coffeescript only runs after a reload.

It was a turbo-links issue. I had to check if turbo-links was loaded properly before attempting to run the rest of the code.
jQuery ->
$(document).ready ->
$(document).on 'turbolinks:load', #Added line
$("#hasUser").change ->
$("#userPart").toggle();
return
return
return
return

Related

Issue with resetting form after submission using Hotwire & Stimulus.js Rails 6

I've been testing Hotwire, using the demo that was put up by DHH. I have a default rails 6 setup & I know that it re-creates the javascript folder structure from the rails 5 < asset pipeline. The issue I am having is the form will not reset the text field after submission - despite setting up the stimulus controller for using this particular action. How can I reset the form for hotwire after the form is submitted by the user? My code is below
new.html.erb
<%= turbo_frame_tag 'new_conversation_comment', target: '_top' do %>
<%= form_with(model: [#conversation, #conversation_comment],
data: { controller: "reset_form", action: 'turbo:submit-end->reset_form#reset' }, html: {class: 'form-inline'}) do |form| %>
<%= form.submit 'Post', class: 'btn btn-primary mb-2', style: 'float: right;', 'data-reset_form-target': 'button' %>
<div style="overflow: hidden; padding-right: .5em;">
<%= form.text_field :content, class: 'form-control' %>
</div>
<% end %>
_conversation_comment.html.erb
<div class="p-1">
<%= conversation_comment.content %>
</div>
show.html.erb
<div class="p-2">
<%= turbo_stream_from #conversation %>
<%= turbo_frame_tag 'conversation' do %>
....
<% end %>
<div class="conversation-comments-container" id="conversation_comments">
<%= render #conversation.conversation_comments %>
</div>
<hr>
<%= turbo_frame_tag 'new_conversation_comment', src: new_conversation_conversation_comment_path(#conversation), target: :_top %>
</div>
assets/javascripts/controllers/reset_form_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
reset() {
this.element.reset()
}
}
Disclaimer: I'm using Webpack 4.0
Depending on setup underscore between controller name can be an issue. Replacing it with dash worked in my case.
turbo:submit-end->reset-form#reset
Disclaimer: I'm using Webpack 4.0
I ran into the same thing, also using Webpack.
The solution for me was:
Change the underscores to dashes, like Canbey said.
Move the stimulus controller from app/assets/javascripts/controllers/ to app/javascripts/controllers/ (somewhat per the stimulus docs so that webpack imported it properly — my application.js file was importing controllers from that directory rather than app/assets/javascripts.
A half SJR, half Hotwire approach would be this:
Working example here: https://rails-react-bootstrap.herokuapp.com/rooms
new.html.erb
<%= turbo_frame_tag 'new_note' do %>
<%= form_with model: [#room, #note] do |form| %>
<!-- Allow body validation error without message -->
<div class="form-group">
<%= form.rich_text_area :body, class: 'form-control comments', id: 'bodyText' %>
</div><!-- .form-group -->
<div class="form-group d-flex justify-content-center">
<%= form.submit 'Add Note', class: 'btn btn-lg btn-tayberry btn-block' %>
</div><!-- .form-group -->
<% end %>
<% end %>
create_js.erb
// clear note textarea after submit
var input = document.getElementById("bodyText");
input.value = '';
notes_controller
def create
#note = #room.notes.create!(note_params)
# #note.user = current_user
respond_to do |format|
if #note.save
format.turbo_stream
format.html { redirect_to #room }
format.js
else
format.html { render action: 'new' }
end
end
end
If you still need an answer, here is how you can achieve what you need:
In your controller respond to requests like that:
format.html { redirect_to conversations_url }
Note: redirect to the page where new_conversation_comment frame is defined (i.e same page from where you are submitting form). Redirect will happen, but Hotwire will substitute form for you with a new one and append comment where you specified.
It is a bit magic.
I suggest you to check this video:
https://gorails.com/episodes/hotwire-rails?autoplay=1

Send f.select parameter to jquery and show dynamic form elements

I have a form who uses a nasted form. I want to him show up when the f.select selects the option unificação.
I using a example that i see in a example, when i select a new option the alert appers, but i don't know how i send the selected element to function and how i tell to him to show the f.fields_for :unifications.
<div class="form-row">
<label>
<span>Evento</span>
<%= f.select :event, ['Reencaminhar', 'Reclassificar', 'Rejeitar alteracão de diagnóstico', 'Rejeitar reencaminhamento', 'Solicitar esclarecimento', 'Cancelar solicitação', 'Rejeitar cancelamento', 'Responder', 'Unificação', 'Envio de cópia de ID', 'Reiterar', 'Registrar Solicitação', 'Reabrir solicitação', 'Complementar solicitação'], {}, :onChange => "fillForm.test(this)" %>
</label>
</div>
<%= f.fields_for :unifications do |unification_form| %>
<label>
<%= unification_form.link_to_remove "Remover cpf" %>
<%= unification_form.text_field :cpf %>
</label>
<% end %>
requests.coffee
#fillForm =
test: ->
alert('Hello world')
Add a div to hide/show the nested form block:
<div id="attributes-to-display" style="display:none">
<%= f.fields_for :unifications do |unification_form| %>
<label>
<%= unification_form.link_to_remove "Remover cpf" %>
<%= unification_form.text_field :cpf %>
</label>
<% end %>
</div>
Its hidden by default. I don't use coffee script, so a possible solution with plain javascript:
// binds the change event
$("#the_select_id").on('change', function() {
// checks if the selected value is what you expect
if ($(this).val() == "whatever") {
// if so, show the block
$("#attributes-to-display").show();
}
else {
// if not, hide the block
$("#attributes-to-display").hide();
// and clean the cpf input box
$("#the_nested_input_id").val('');
}
});
You need to replace the ids (#) with the correct form ids, as I don't have enough information to provide it.

Rails Kaminari example infinite scroll not working

I am trying to implement kaminari rails infinite scroll using this example.
It is working fine in my other apps but not working in this app.
Kaminari example
My company controller
def index
#companies = Company.all.page(params[:page]).per(4)
end
My index.html.erb
<div class="posts">
<div class="page">
<%= render #companies %>
</div>
</div>
<%= paginate #companies %>
My _company.html.erb
<div class="post">
<% company_decorator = CompanyDecorator.new(company)%>
<h4><%= company.name %> ||
No. of operations: <%= company_decorator.number_of_operations %> ||
Average Amount : <%= company_decorator.average_of_amount %> ||
Highest of Month: <%= company_decorator.highest_of_month%> ||
Accepted Operations: <%= company_decorator.accepted_operations%>
</h4>
<ul>
<% company.operations.each do |operation| %>
<li><%= operation.id%></li>
<%end%>
</ul>
</div>
My assets/javascripts/companies.js.coffee
$(document).ready ->
$(".posts .page").infinitescroll
navSelector: "nav.pagination"
nextSelector: "nav.pagination a[rel=next]"
itemSelector: ".posts .post"
My index.js.erb
$(".posts").append("<div class='page'><%= escape_javascript(render(#companies)) %></div>");
I am unable to find problem please help me. This same code is working in my other app.
Try
def index
#companies = Company.all.page(params[:page]).per(25)
end
playing with the pagination length.. I've heard that sometimes works

.load() Jquery function load duplicate window in the same time

I have the Jquery code below:
$(document).ready(function() {
$('tr[href]').click(function(event) {
$('tr[href]').removeClass('selected')
$(this).addClass('selected');
event.preventDefault();
$('#profile').load('home/users/1');
event.stopPropagation();
});
});
Every time I click the target, I found the .load function load the window double times the last click. For example, in the rails log it shows several Started GET "/home/users/1in the same time thus my app becomes slow and slow. Below is the view file where the window is loaded:
<div class="col-md-5" >
<div class="table table-responsive" >
<div id='list' >
<% if params[:q] == 'a' %>
<%= render 'users' %>
<% elsif params[:q] == 'b' %>
<%= render 'jobs_index' %>
<% else %>
<%= render 'lineitems' %>
<% end %>
</div>
</div>
</div>
<div class="col-md-5">
<div id="profile">//load the window
</div>
Could any body tell me why this occurs? Very thanks!
I solved it.
I modified the code $('#profile').load('home/users/1'); in application.js as below:
var url="home/users/"+$(this).attr("href")
$('#profile-outline').load(url+" #special");
And add a in the outermost of the html file.Then the problem is solved.
In summary, just use load("url #container") to replace load("url").

resetting form via jQuery not clearing ckeditor cktext_area field

I have following form
<div id="post-close-updates-form">
<%= form_for [#investment,#post_close_update], remote: true do |f| %>
<div class="form-group">
<%= f.label :content %>
<%= f.cktext_area :content %>
</div>
<%= f.submit "Update", class: "btn btn-primary" %>
<% end %>
</div>
and my jquery code is
$("#post-close-updates-form form")[0].reset();
but it is not clearing cktext_area content...while if i put normal html textarea then it works fine.
so how do i clear ckeditor cktext_area via js/jquery
ok here is the answer given by developer of ckeditor #galetahub
$("#post-close-updates-form form")[0].reset();
for (instance in CKEDITOR.instances){
CKEDITOR.instances[instance].updateElement();
}
but above one not worked for me so made some chages that works
for (instance in CKEDITOR.instances){
CKEDITOR.instances[instance].setData(" ");
}
setData() is to set the data is cktext_area
now if u want to get the data from cktext_area in js then use this
for (instance in CKEDITOR.instances){
CKEDITOR.instances[instance].getData();
}

Categories

Resources