How do I limit the number of form fields I can add with jquery?
I followed the instructions in Railscasts #197 http://railscasts.com/episodes/197-nested-model-form-part-2 about how to add links that dynamically add form fields in rails. This is awesome! I never would have figured this out on my own.
I'm trying to figure out if there is a way to limit the number of fields that a user is allowed to add. For instance, I may start with 2 fields by default, but want to make a maximum of 5 fields total. (ie开发者_开发技巧 in the survey example I could default to 2 answers, but want to make sure that there are no more than 5).
(Small thing: Does anyone know how to make the new field slideDown() instead of just appearing?)
If you are creating elements dynamically, you can limit it by using following code:
if($("input,select").length <5){
//create element dynamically
}
Also check this tutorial
jQuery - Dynamically Adding Form Elements
It is important to notice that if it is a relevant constraint, you should also ensure this limit at the server side as you have no control over what is done at the client browser alone.
You can do this by adding something like this in your Parent
model:
accepts_nested_attributes_for :children, allow_destroy: true, limit: 5
This way it will throw a exception in case someone tries to break it.
精彩评论