I have a form in a bootstrap modal window that works perfectly - results are posted to the window upon form submission. This form is hardcoded into the html for the page.
Now i'm trying to load the form remotely. It loads the form just fine (puts it into modal-body). However, now when I click submit the modal goes away and the whole page goes to the form url.
Do i need to define my binding on the parent page, or in the remote url? My thought is that on pageload the id of the remote form is not known to the DOM. Also not sure if the remote url can reference a div on the parent page.
So it seems I'm out of sync - the parent DOM doesn't recognize the form since it's remote, and not sure that the remote form can bind to modal defined in the parent.
Any thoughts?
thanks!
from parent page:
<div class="modal hide fade in" id="mymodal">
<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button></div>
<div class="modal-body"></div>
</div>
load remote url here:
<a class="tip" data-toggle="modal" data-target="#mymodal" href="/index.php/change_delivery/change/2" rel="tooltip" title="Change Delivery Date"><i class="icon-calendar"></i></a>
form from remote url:
<form class="form-horizontal" id="delivery_date_form" action="/change_delivery/submit_change">
....
</form>
and at the end of the remote url/form:
<script>
$(function() {
$('#delivery_date_form').bind('submit', function() {
$.ajax({
url: "change_delivery/submit_change",
type: "POST",
dataType: "html",
contentType: "application/html",
success: function(msg) {
// this is returned value from your PHP script
//your PHP script needs to send back JSON headers + JSON object, not new HTML document!
// update your "message" element in the modal
$("#modal-body").text(msg);
}
});
});
});
</script>
This is how I do it:
$(function(){
var $mymodal = $('#mymodal');
$('[data-toggle=modal]').click(function() {
$mymodal.attr('data-form-action', $(this).attr('data-remote'));
});
$mymodal.find('.save-button').click(function() {
$.post($mymodal.attr('data-form-action'), function(data) {
$mymodal.find('.modal-body').html(data);
});
});
});
Related
<%= f.radio_button :newCustomer, "Male",:value=>'NewCustomer',:checked=>true%>
`<%= f.radio_button :customer, "Female",:value=>'Customer'%>`
<div id="first"></div>
<div id="second"></div>
I am new in rails.I have two radiobuttons and two div.When i click NewCustomer i want to hide first div and when i click on the Customer show the hidden div.I want to do this in only Ruby code.Is there any radiobutton click event like in .net
You can achieve it by Javascript / JQuery / Ajax in rails:
Example:
HTML
<input type="radio" name='thing' value='valuable' data-id="female" />
<input type="radio" name='thing' value='valuable' data-id="male" />
<hr />
<div id="female" class="none">Div for Male</div>
<div id="male" class="none">Div for Female</div>
CSS:
.none {display:none;}
JQuery
$(':radio').change(function (event) {
var id = $(this).data('id');
$('#' + id).addClass('none').siblings().removeClass('none');
});
Working Fiddle
Pipeline
To further Gagan's answer, you'll want to include your Javascript in the asset_pipeline:
#app/assets/javascripts/application.js
$(document).on("change", ".radio", function(){
// gagan's code here
});
--
Turbolinks
Something to note is the importance of the javascript "delegation" - when you use Rails applications with Turbolinks.
Because of the way in which Turbolinks will just update the <body> tag of your page, many JS event bindings will actually become invalid, preventing your application from loading correctly.
To fix this, you need to be able to either delegate your DOM events from a "container" element (typically document), or by encapsulating your code in Turbolinks events like so:
#app/assets/javascripts/application.js
var change = function() {
$(".radio").on("change", function(){
//Stuff here
});
};
$(document).on("page:load ready", change);
i have a model, which i want to show edit and update in a dialog via ajax.
What i do at the moment:
To open the Modal and render the partial, i send an ajax request to controller#show with ujs
this is the link:
<a class="person-dialog" data-remote="true" data-type="script" href="/en/people/32"
onclick="return false">Fidel Markus Armstrong</a>
this runs the script in new.js.erb which renders the show partial inside the dialog and opens it.
To get the edit form, i do the same
<a class="person-dialog" data-remote="true" data-type="script"
href="/en/people/32/edit" onclick="return false">Fidel Markus Armstrong</a>
this runs edit.js.erb
Now: To update my model, i send the form data as json to the controller#update
<form accept-charset="UTF-8" action="/en/people/32" class="form-horizontal"
data-remote="true" data-type="json" id="edit_person_32" method="post">
if there is an error in the form, i do render_to_string(form_partial) inside the controller and respond with this inside of the json response.
Now i have the partial html inside of the json object. I do this, to get the rails error messages and fields_with_errors.
Is there a better way to do it? all the mix between script and json format and the partial html inside the json doesn't feel right.
This is the ajax.success for the form submit:
$('#dialog').on('submit', ->
$(this).find('form').bind('ajax:success',(evt, data, status, xhr) ->
if xhr.status == 201 # :created
url = data.url #this is en/people/:id
#Load show dialog on success - runs show.js.erb
$.ajax({
url: url,
type: 'get',
dataType: 'script'
})
else
#Render the dialog html including the error messages and fields with errors
#data.error is the partial
$('#person-dialog').html(data.error)
$('.field_with_errors input').first().trigger('focus')
$('.modal-header').prepend('edit')
)
please comment, if the question is not clear enough
i'm making an Ember app with a Rails back end. In one of the templates, I list the available teams from a database and beside each team put a form field for the user to enter some textual information. If I enter information in one form field, the text appears in all of the form fields (kind of like a multiple cursor experience). That's one problem. Also, when I submit the button to attend one of the conferences, nothing's happening in the controller. I'm wondering if this is a related problem as Ember might think I'm trying to submit from multiple forms at one time due to the fact that these forms are acting as if they're the same form.
Can you see what I'm doing wrong?
<script type="text/x-handlebars" id="conferences">
<div class='span4'>
{{#each item in model}}
<li> {{#link-to 'conference' item}}
{{ item.name }}
{{ partial 'conferences/form'}}
{{/link-to }}</li>
{{/each}}
</ul>
</div>
<div class="span4 offset4">
{{ outlet}}
</div>
</script>
Inserted Form
<script type="text/x-handlebars" id="conferences/_form">
<form class="form-horizontal" {{action "attend" on="submit"}}>
<div class="controls">
{{input value=username type="text"}}
</div>
<button type="submit" class="btn">attend</button>
</form>
</script>
Conferences controller
App.ConferencesController = Ember.ObjectController.extend({
actions: {
attend: function() {
console.log('this is not logging, & no indication rails route is posted to)
$.post("/join_conference_path", {
username: this.get("username"),
}).then(function() {
document.location = "/";
}, function() {
}.bind(this));
}
}
});
Having all input values synced to the same text happen due to fact that each input value is bound to the same property username.
This happens because all _form partials are rendered in the same context which is in your case App.ConferencesController. To make them render in individual context use itemController argument for each helper. See spec here: http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_each
{{#each item in model itemController="conference"}}
In this case I suggest you rename your App.ConferencesController to App.ConferenceController which will represent individual context for each "item". Having it done this way your action will always use username input for specific "item" only.
Action may not trigger because by default all actions targets routes and not controllers. Try to add target="controller" attribute to action helper:
{{action "attend" on="submit" target="controller"}}
I'm using backbone jquery mobile and coffee script to develop a simple twitter application. My problem is the jquery mobile styles are failing to render. My View is
class HomeView extends Backbone.View
constructor: ->
super
initialize: ->
#Twitter= new TwitterCollection
template: _.template($('#home').html())
render: ->
#loadResults()
loadResults: ->
#Twitter.fetch({
success: (data) =>
$(#.el).html(#template({data: data.models, _:_}))
error: ->
alert('Error!')
})
This works fine in terms of pulling information from Twitter, however when
$(#.el).html(#template({data: data.models, _:_}))
is within the fetch function, jquerys styles do not render. Can anyone show me how to refresh the styles? Help would be much appreciated!
For reference, the html template is:
<script type="text/template" id="home">
<div data-role="header" data-position="fixed">
<h1>TWITTER DATA</h1>
</div>
<div data-role="content">
<ul data-role="listview" data-inset="true">
<% _.each(data, function (row) { %>
<li><%= row.get('text') %></li>
<% }); %>
</ul>
</ul>
</div>
Ok, I fixed it by adding ".listview('refresh').trigger('create');" to the end of
$(#.el).html(#template({data: data.models, _:_}))
When the fix is applied afterwards (after the view page has been rendered and displayed by $.mobile.changePage()) the user gets an unpleasant side-effect: the view flickers due to the change of style applied by jquery mobile.
My solution to the problem was to trigger custom event from the view once the dynamic rendering is complete and bind the $.mobile.changePage() to that event. This causes the output to be "buffered" until complete and then styled altogether.
Here's an example:
In the initialize function of my view I have code waiting for an event to be fired by the model/collection when fetched and a function to render the dynamic part of the html:
window.MyView = Backbone.View.extend({
// some other code here
initialize: function() {
this.listenTo(this.collection, "fetchCompleted:CollectionName", this.renderRows);
},
renderRows: function (eventName) {
$(this.el).find('div[class="content-primary"]').html(this.template_ul({data: this.collection}));
this.trigger( 'view:ready' );
},
//...
... then in the router I have the following code for the changePage():
myViewObject.on( 'view:ready', function() {
$.mobile.changePage($(next.el), {changeHash:false, transition: transition});
});
I want to show modal window on click of link but also want to do ajax request to get the object which needs to be shown on modal window.
I am getting response with the content which needs to be shown on modal window but it is not popping up as modal window probably the script is not getting executed.
Code
Main Page
<%= link_to "New Topic", "#", :class => 'btn primary float-right bootstrap-popover' %>
<div id="modal_form_container"></div>
Javascript Code
$('a.bootstrap-popover').live('click', function(){
$(this).unbind('click');
$.ajax({
url: "/topics/new",
type: "GET",
dataType: "html",
complete: function() {
$('loading').hide();
},
success: function(data) {
},
error:function() {
}
}); // End of Ajax
new.js.erb
$('#modal_form_container').html("<%= escape_javascript( render :partial => 'new_form')%>");
$('#modal_form').modal('show');
This new_form page contains content to be shown on modal window
Can anybody help?
Is it because the loading element is not being hidden?
$('loading').hide();
Should this not be something like:
$('#loading').hide();
I think you have to write something like following code after your ajax request gets success.
$('#PopupBoxId').modal('show'); // Show the pop-up (modal)
$('#disable_layer').modal('show'); // Show the black overlay
We have to manually show the pop-up after the ajax request handling.. As per my small experience in bootstrap.
:)
Hope it works for you.
Have you looked into the Bootstrap Modal Manager? You can use it like so:
$("a.open-with-ajax-loader").live('click', function(e){
e.preventDefault();
$('body').modalmanager('loading');
$('#id-of-modal-div').modal({
remote: '/url/to/load'
});
});
You can see this in action on the live demo page for the Bootstrap Modal Manager ( scroll down a bit, look for the AJAX demo ).