The prototype only serializes the visible value of the form field
Is it possible to prototype.js
serialize only visible form field values. I have a form where elements have the same name, but one is visible, but the other is hidden. When I serialize the form with $('formid').serialize()
then both field values come in and the output looks like this:
user_email=abc@example.com&mymodule_custom_delivery_area=20&mymodule_custom_delivery_area=test
The first item was a dropdown when the second was a textbox. The text box was hidden and dropped out. Both have the same name. I don't want to accept the value of a hidden textbox. How can i do this? Thanks to
source to share
Warning . Incomplete solution; feel free to use it as a starting point for a better solution:
Unfortunately I haven't found a good way to do this in general, but the following solution works for me if the input element is directly hidden; however, it does not work if any input is contained in another element, which in turn is hidden.
Anyway, my solution looks like this:
function check() {
var inputs = $("myform").getElements();
var visibleInputs = inputs.grep({ match: function(elem) { return elem.visible();} });
var serialized = Form.serializeElements(visibleInputs);
console.log(serialized); // here do something useful with it instead
}
On the first line, it collects a list of all the form fields. On the second line, it filters all visible items from this ( grep
needs an item with a function match
, so I provided a simple dictionary with a key match
to trick it into thinking that I am passing it to matches). Finally, only the filtered elements are serialized.
Please: can anyone improve this to exclude input fields that are not visible because the hidden element is hidden? I can only think of a complex function match
that picks up all the parents and checks each one separately if hidden.
source to share