elclanrs / jq-idealforms-old

The ultimate framework for building and validating responsive HTML5 forms.
665 stars 95 forks source link

2 questions about addFields() #65

Closed obxpete closed 12 years ago

obxpete commented 12 years ago

q1: why create your own format for passing data to addFields() instead of using json?

q2: I'm having problems with javascript to create the proper addFields format. below is my broken code. It simply gives me a drop-down list (in FF) with each entry simply saying "[object Object]". Please advise.

                var newField = [{
                    name: data.newField.name,
                    label: data.newField.label,
                    type: data.newField.type,
                    filters: data.newField.filters,
                    data: data.newField.data,
                    list: $.each(data.newField.list, function() 
                            {'"'+this.label + ':' + this.value +'"'}
                            )
                    }]

                     $idealform.addFields(newField)
elclanrs commented 12 years ago

Your problem is in list. You have to make sure to pass the format that it expects, in this case an array. Your $.each loop is not returning anything plus this inside of it means nothing relevant. $.map will get you the array you're looking for assuming that your list object looks like this:

data.newField.list = [
  { label: 'foo', value: 'f' },
  { label: 'baz', value: 'b' }
];
list: $.map( data.newField.list, function( item ) {
  return item.label + ':' + item.value
})

I made the lists work like that because it's faster to write and less verbose but maybe you're right about JSON format...

Btw, if you're passing just one field you don't need to wrap it in an array, you can just pass the object. Hope this helps. Thanks for your contribution to the project.

obxpete commented 12 years ago

You're a prince! For future users, I'm posting the working code below. Note: the $.makeArray() was important, presumably because the request is returned on JSON format, so it had to convert from object literal to array. SWEET!


    $.ajax({
            url: '....',
            type: "GET",
            dataType: "JSON",
            async: "false",
            success: function(data){

                var newList = $.makeArray(data.newField.list);

                var newField = [{
                        name: data.newField.name,
                        label: data.newField.label,
                        type: data.newField.type,
                        filters: data.newField.filters,
                        data: data.newField.data,
                        list: $.map(newList, function(val, i )
                            {
                                return  val.label + ":" + val.value
                            }
                            ) 
                        }]

                $idealform.addFields(newField);

            }
    })