Reputation: 32190
I'd like to have a field that doesn't show at first, but if the user decided to input to it, then it will appear in the form.
I can use Jquery and do something like
$('input[example]')
.bind('click', function() {
$('#clickfield')
.append('<input id="new_field" name="MODEL[new_field]" size="30" type="text">');
However, I'd like to add this field in several different forms for different models. Since the model name is in the field, how would I write the Jquery script to be modular so I can use the same script for all my forms?
Upvotes: 0
Views: 127
Reputation: 4038
One solution is to make a function with the names you want as input parameters:
addInput(form, id, modelName) {
$(form).append(
'<input id="'+id+'" name="'+modelName+'['+id+']" size="30" type="text">'
);
}
Where form
would be the selector of the field ('#clickfield'
in the example case), id
would be the id of the new input field, and modelName
would be the name of the model you mentioned.
Other solution, assuming 'input[example]'
selects some button or clickable area that triggers the event of showing the field; and '#clickfield'
is some div
or span
or some area where you will show your field, is to load these hidden fields from the server, styled as display:none
, with a mnemonic class, so you could do something like define a function:
showField(clickable, class) {
$(clickable).click(
function(){
$(class).show();
}
);
}
and then:
$(document).ready(
showField('input[example1]', '.class1');
showField('input[example2]', '.class2');
showField('input[example3]', '.class3');
// .
// .
// .
// One line for every clickable area that triggers
// the event of showing a field, and the class of the
// field to show
);
this way you could add some user friendly features like fading the field in with the fadeIn()
Jquery function (instead of show()
), or any other animation on appearing.
Hope you could use it! good luck!
Upvotes: 2