
10/04/2013, 15:59
|
 | | | Fecha de Ingreso: junio-2003 Ubicación: Madrid
Mensajes: 386
Antigüedad: 21 años, 10 meses Puntos: 3 | |
Generar select mediante jQuery Hola a todos,
Tengo un problema con una funcion en Jquery que pinta formularios dinámicos vacíos cuando se hace click en un botón de "Añadir" y que permite rellenarlos y enviarlos a la base de datos.
Las propiedades de los campos se proporcionan en un array:
Código:
//Más arrays
agency_services:{
'title':'Services',
'item':[
{
'name':'agency_services[date]',
'class':'agency_services-date',
'type':'datetime',
'label':'Date'
},
{
'name':'agency_services[type]',
'class':'agency_services-type',
'type':'text',
'label':'Services'
},
{
'name':'agency_services[services_type]',
'class':'agency_services-services_type',
'type':'select',
'label':'Services type'
},
{
'name':'agency_services[service_status]',
'class':'agency_services-service_status',
'type':'text',
'label':'Status'
},
{
'name':'agency_services[id]',
'type':'hidden',
'primaryKey':true
},
{
'name':'agency_services[agency_id]',
'type':'hidden',
'foreignKey':true
},
{
'type':'action',
'action':'delete'
}
]
},
//Más arrays
Y luego mediante una función BuiltIteam que genera esos campos de formadinámica. Con los campos de texto, hidden y demás no tengo problemas porque ya hay varios programados pero necesito hacerlo también con un campo tipo "select" y he hecho mil pruebas y no consigo que se pinte correctamente en el formulario.
La parte que estoy intentando hacer es la que tiene el comentario:
//Esta es la parte de Select
Y que no consigo hacerla funcionar.
La función builtItem es la siguiente:
Código:
function buildItem(itemArray, parentId, isColumn){
isColumn = (isColumn===true);
var el, wrap, rwrap, lbl, id, sec;
var $form = (isColumn)?$('<div />',{'class':'column'}):$('<form />',{'action':'', method:'post'});
var $item = $('<div />',{'class':'item'});
$.each(itemArray,function(i,attrs){
// Array of fields (column)
if($.isArray(attrs)){
if(!isColumn) $form.append(buildItem(attrs,parentId,true));
// Hidden input
}else if(attrs.type=='hidden'){
el = $('<input />',{
'type':'hidden',
'name': attrs['name']
});
if(attrs.primaryKey){
// Convention... new parents get a unique id, starting with pk as a placeholder
// for a real id for him and its children
el.attr('value','pk '+_increment);
_increment++;
}
if(attrs.foreignKey){
// Convention... children of new items get special Id because their
// parent does not have an id yet... Parent algo get special id: pk # and fk #
var pk = parentId.split(' ');
if(pk.length<2) el.attr('value',parentId);
else el.attr('value','fk '+pk[1]);
}
if(attrs.hasOwnProperty('value')){
el.attr('value', (typeof attrs['value']==='function')?attrs.value():attrs['value'] );
}
$form.append(el);
//Esta es la parte de Select
}else if(attrs.type=='select'){
wrap=$('<select />',{
'type':'select',
'name': attrs['name']
});
if ($.isArray(attrs['options'])) {
for (var opt in attrs['options']) {
el = $('<option />',{
'value':opt['data']
});
name = $(attrs['name']).text();
wrap.append(el).append(name);
_increment++;
}
};
// Text & Date fields
}else if(attrs.type=='text' || attrs.type=='date' || attrs.type=='datetime' || attrs.type=='file'){
wrap=$('<div />',{'class':(attrs["type"]=="file")?'input-file ':'input-text '+attrs['type']});
lbl=$('<label />').text( (typeof attrs['label']==='function')?attrs.label():attrs['label'] );
el=$('<input />',{
'type':'text',
'name': attrs['name']
});
if(attrs.hasOwnProperty('value')) el.attr('value',(typeof attrs['value']==='function')?attrs.value():attrs['value']);
if(attrs.hasOwnProperty('class')) wrap.addClass(attrs['class']);
$('<div />').append(lbl).append(el).appendTo(wrap);
$form.append(wrap);
// Radio fields
}else if(attrs.type=='radio'){
rwrap=$('<div />');
if($.isArray(attrs['options'])){
for(var rad in attrs['options']){
id='radio-'+_increment+'j';
el=$('<input />',{
'id':id,
'value':rad['data'],
'name': attrs['name']
});
lbl=$('<label />',{
'for':id
}).text(rad['label']);
rwrap.append(el).append(lbl);
_increment++;
}
}else{
// Get values from data source with ajax...
}
if(attrs.hasOwnProperty('value')) $('input',rwrap).val( (typeof attrs['value']==='function')?attrs.value():attrs['value'] );
lbl=$('<label />').text( (typeof attrs['label']==='function')?attrs.label():attrs['label'] );
wrap=$('<div />',{'class':'input-radio'})
if(attrs.hasOwnProperty('class')) wrap.addClass(attrs['class']);
$('<div />').append(lbl).append(rwrap).appendTo(wrap);
$form.append(wrap);
// Actions (for now, only 'delete')
}else if(attrs.type=='action'){
$form.append('<a class="delete" href="#remove"><span>Delete</span></a>');
// Empty section
// Empty section
}else if(attrs.type=='section' && !isColumn){
sec = $('<div />',{'class':'section '+attrs.id});
sec.append(
'<div class="header">'+
'<h2>'+__template[attrs.id]['title']+'</h2>'+
'<a class="add'+((__template[attrs.id]['add']=='prepend')?' prepend':'')+'" href="#add"><span>Add new</span></a>'+
'</div>'
);
if($('input',$form).length){
$item.append($form);
$form = $('<form />',{'action':'', method:'post'});
}
$item.append(sec);
}
});
if(isColumn) return $form;
if($('input',$form).length) $item.append($form);
return $item;
}
Ah, y los valores options del select van en este array:
Código:
var servicesCategories = {
'1': 'Servicio 1',
'2': 'Servicio2',
'3': 'Otros'
}
¡Saludos y muchas gracias de antemano! |