Extract UI elements with values and id from a html form and ignore null elements and FALSE checkboxes

311 views Asked by At

I have generated several forms using METAWIDGET where i pass a light weight JSON now I want to extract the values of the ui elements along with their ids and then bind it to a string to pass it as a URL parameter.

Now I can write Javascript to extract the UI elements and values from the form but if you have a form with more than 40 options and the same no of elements are present for other forms then it becomes difficult to individually extract the values from the ui element. It would be great if anyone has come around such API in Javascript which extracts the UI element values and ID automatically it would be great if you can share the same.

Thanks!

1

There are 1 answers

0
Richard Kennard On

Metawidget already provides such a capability. You can use:

var processor = mw.metawidget( "getWidgetProcessor", function( widgetProcessor ) {
    return widgetProcessor instanceof metawidget.widgetprocessor.SimpleBindingProcessor;
} );
processor.save( mw.data( 'metawidget' ) );

To retrieve the SimpleBindingProcessor (that is configured by default) and call its save method. This will save the contents of all UI elements back into the mw.toInspect. There's an example here. Note some flavours of Metawidget (such as Angular Metawidget) do this automatically.

If you're specifically concerned about capturing the IDs of the elements, you can extend SimpleBindingProcessor and override its saveFromWidget method:

var bindingProcessor = new metawidget.widgetprocessor.SimpleBindingProcessor();
var superSaveFromWidget = bindingProcessor.saveFromWidget;
bindingProcessor.saveFromWidget = function( binding ) {

    // access binding.widget.getAttribute( 'id' ) and save it somewhere
    ...
    return superSaveFromWidget.call( this, binding );
}

This will get triggered when you call processor.save as before.