Update attribute on check box click (Rails 3) - ruby-on-rails

I've been searching forever to find an actual answer to this:
What would be the best way to update an object's attribute via ajax when a checkbox is clicked? It's simply a matter of wanting to flip an attribute from false to true and vice versa.
There are one or two threads on stackoverflow about this, but they either employ observe_field (I'd rather just do it with a Prototype function) or have never solved the problem at all, it seems.
Again, this is Rails 3 and Prototype.

I guess it's the checkbox part that's tripping you up?
All you really need to do is have a method in your model to toggle the appropriate field
# somewhere in your model
my_boolean_field.toggle
and then bind a .click() handler to your checkbox to do an ajax request. If you need to, in the .click() handlers callback you can update the checkbox but I'm not sure if that's necessary.
The only part that's tricky here is what to do if the user clicks the checkbox quickly several times. One option is to disable the checkbox after it's clicked until the callback finishes.

Related

Conditional show/hide fields based on show/hide links

What I try to do is very simple.
I have some fields in a form that are optional to fill. To make the form look cleaner, I'd like to show simple links as Add field and display the optional fields below via js unobstructedly.
If the field is present, it will be saved into the database. The field would also have a delete link. When this delete link is clicked, the field will be removed and also its value from the database when saved.
Seems pretty simple, yet I haven't found a simple approach to this. The whole solution involves many aspects such as passing hidden data to the controller to see if the record was hidden in order to delete its data from the database.
I would prefer a gem already optimized for this purpose but I couldn't found any. What I found is intended for associated records but this is not the case. These are not associations, just optional attributes from the same model.
nested_form_fields gem its also not suitable since it needs a checkbox or radio button to be triggered and not Add field/Remove field links which I believe look cleaner.
Is there such thing as a gem to accomplish this simple thing?
Instead of trying to send hidden data etc. Why don't you just load all the form fields but display:none. When a user clicks the 'show' button you display the field. If the click the hide button, just set the field to null and hide it.
When your form reaches the controller it will save the null value to the db for the hidden fields (same as if you deleted the value).

making unobtrusive validation work when using Select2 ASP.NET MVC

Select boxes converted to Select2, do not automatically integrate with unobtrusive validation mechanism in ASP.NET MVC framework.
For example, on a form which contains a regular select box (marked as required in model definition), submitting the form while no options have been selected in the select box, will cause the border and background of the select box to take a reddish color, and by using #Html.ValidationMessageFor, error messages, if any, can be displayed beside the box. However if the select box is converted to a Select2 component, then none of the mentioned features work any more. Even the validation error message will not show up.
It seems that the reason for even the validation error message not showing, is because Select2 changes the display CSS property of the original select box to none (display:none), and I guess the unobtrusive validation script does not bother generating error messages for invisible fields.
Any ideas / solutions?
This issue isn't really specific to Select2, but rather to the jQuery unobtrusive validator.
You can turn on validation for hidden fields as highlighted in this answer.
$.validator.setDefaults({
ignore: ''
});
As the comments noted, it didn't work inside an anonymous callback function within $(document).ready(). I had to put it at the top level.
I've run into similar issues with the select2 plugin. I don't know exactly which features you're using specifically, but in my experience, when you set an element as a select2 in the document.ready event, the plugin will change some of the element's attributes on the fly (inspect one of the elements after your page has finished loading - oftentimes you'll see the id and class properties are different than what you're seeing when you view source).
It's difficult to offer more without actually seeing the code, but here's a few ideas to get you started:
First off, obviously make sure you have the a link to your select2.css stylesheet in the header.
Then, since you're talking about form submissions, I'd recommend you examine whether or not you're getting a full postback or submitting via AJAX (if you're using jQueryMobile, you're using AJAX unless you override it in the jquerymobile.js file or set a data-ajax="false" in your form attributes). You can just look at the value returned by Request.IsAjaxRequest() for this. Obviously if you're submitting via ajax, you won't hit the document.ready event and the select2 won't initialize properly and you'd need to figure out a way around that. Try refreshing the page after the submit and see if it renders the select2 component.
Then I'd suggest examining the elements and see if they're not behaving like you'd expect because you're actually trying to work with classes that the plugin has reassigned at runtime. You can either just adjust your logic, or you can dig into the select2 code itself and change the behavior - it's actually fairly well-documented what the code is doing, and if you hop on the Google group for select2, Igor is usually pretty quick to follow up with questions.
like this
$('select').on('select2:select', function (evt){
$(this).blur();
});
$('body').on('change', 'select.m-select2', function () {
$(this).blur();
})

How can I manipulate a form / inputs to be ignored when a form is submitted

I'm using ExpressionEngine and SafeCracker along with Ajax (plugin: jquery.form.js - http://jquery.malsup.com/form/).
Best I can tell, SafeCracker will only allow for updating a single entry at a time. However, the UI / UX necessitates that a list be displayed. I've proof of concept'ed an entry by entry on-demand form. That is, click a particular edit link next to each entry and a snippet of jquery creates a form along with displaying a submit button. Click submit and that single entry updates. The inputs don't exist until the Update link is clicked
What I would prefer to do, if possible, is to create the non-form and form versions of each entry as the page is renbered and use some sort of toggle to display one or the other. Again, doable. Then, when I click the Edit link I'd add the necessary attributes to the input so that entry's form elements will be read but the other (display: none) elements for the other entries will be ignored. I'm thinking (out loud) that if I add the attr("name", some-value) that would work. That is, an input with no name will be ignored.
Yes, I can test this and I will. However, even if it works I'm not sure if it's a best practice and/or there's a more ideal way of accomplishing my ends. I'm here looking for validation and/or additional expertise and input.
Thanks in advance.
Just set disabled property to inputs and they will excluded from Form submission, whatever input fields are hidden or visible. Different jQuery methods, like submit() and serialize() follow specification of HTML 4 and exclude all disabled controls of a forms. So one way is to set
$('your_input').prop('disabled', true);
or ,
$('your_input').attr('disabled', 'disabled');
Check following link:
http://www.w3.org/TR/html401/interact/forms.html#successful-controls
Also, you may use a general button instead of a submit, as result you can handle click event on it and within that event you can make exclusion, validation, manipulation on values and what ever you like.
You can put a disabled attribute on them server side or set the property via jQuery:
$(".hidden input").prop("disabled", true);

Creating ajax-enabled subform with "Edit" button

I am looking for the best way to create ajax enabled subforms from items in a list with MVC 3. A static list of values should be generated, but with an "edit" link/button next to every item, to toggle inline edits.
I did follow the tutorial at this link
http://blog.janjonas.net/2011-07-24/asp_net-mvc_3-ajax-form-jquery-validate-supporting-unobtrusive-client-side-validation-and-server-side-validation [1]
However it is based on the form edit fields always being visible
I'd like to show a static list with field values, but let the user activate an edit field by clicking "edit" (e.g. button)
I did modify the example at [1] by creating a default partial view with a form with submit button only. When posting the data by ajax the edit form will show. It looks like it is working, (I only need to hide validation errors on the first POST - which does not send real data).
Update:
An even better solution would probably be to leave out all forms in the static view, just have a single css class button/link next to each item, and let jquery fetch the relevant view for the clicked item. I am not sure how to do that with MVC 3+jQuery though.
Another update:
I discovered Ajax.Actionlink, which did exactly what I wanted!
I found out how to do it, and it turned out to be real simple!
I created two partial views.
One for rendering each static item. I used used Ajax.ActionLink with InsertionMode "replace", and set the parent of the item as the target
The second for rendering the form. Here I used Ajax.Beginform with similar options.
On successfully saved data, I returned the static view, on failure, I returned the partial view with the ajax form again.
I'm happy I found a MVC-centric way to do it (although it is fun creating custom stuff with jQuery)
It sounds like you need an inline editing plugin for jQuery. I would try jEditable. I have not used it myself but appears to have extensive docs.
this entry might help: code + video + explanation ;)
http://ricardocovo.wordpress.com/2011/04/03/asp-mvc3-editing-records-with-jqueryui-dialogs-and-ajaxforms/
-covo

Rails: Prevent duplicate entry from simultaneous submission

We're having a problem with our app allowing people to sign up multiple times with the same account information (email, specifically).
Our user model validates the uniqueness of the email parameter, and we are also using some javascript to make sure that once the "sign up" button is clicked, it becomes unusable unless the sign up fails (theoretically ensuring only a single click).
It appears that the problem stems from users double-clicking the signup button before the javascript on the page finishes loading.
Is there a way from the Rails side that we can prevent this? Maybe something that creates a request stack, and then iterates through them? I ask because we can't be the only site that has this issue.
Thanks
Dumb question: Why don't you set the field in the database itself to unique?
If that is not possible, do what Steve Bourne suggested and use something like this:
var clicked = false;
$('#submit_button').click( function() {
$(this).preventDefault();
if(!clicked) {
clicked = true;
$('#submit_button').attr('disabled','disabled');
$('#form').submit();
}
Now, I didn't test that so setting clicked = true may be overkill ;)
Set the text field to Nothing right after the insert.
Not entirely convinced that's what's happening, but another option would be to only enable the submit button in jQuery's ready function, and start off with it hidden or disabled. Are you running a large amount of JS outside of the ready function?
If the problem is that users submit the form before your javascript is finished loading, why not make that impossible? (i.e. the submit button action doesn't submit the form, but your javascript submits on the click event?)
There are a few ways to then prevent dupes in JS; sounds like you've got that covered already.

Resources