0

I want to get a jQuery object representing the exact collection of elements whose data would actually be submitted. So, part one is how does the browser decide which fields to submit, and part two is how to get jQuery to select that set. (I've found many answers on actively adding to or subtracting from the set of submittables, but almost nothing on passively determining them.)

Ideally there's a closed-form selector expression for these elements. The best I've come up with however has an elaborate .filter() function.

var $submittables = $('#myform').find('[name]:input:not(:button)').filter(function () {
    if ($(this).is(':checkbox:not(:checked), :radio:not(:checked)')) {
       return false;
    }
    return !$(this).prop('disabled');
});

Is this accurate? Is there a leaner way?

I gather $('#myform').serializeArray() will get the name-value pairs rather succinctly, but that's not simple to translate into a collection of elements, e.g. with only the checked radio buttons and checkboxes.

The goal is to be able to iterate through these form elements with .each(). My own application is to clone or disable some fields at submit-time based on data properties, so I want the jQuery objects, not just the name-value pairs. Here's an oversimplified use of the collection:

$submittables.each(function () {
    console.log("name", this.attr('name'), "value", this.val());
});

The answers to "How to loop through all elements of a form jQuery" either include elements that will not be submitted, or provide just the name-value pairs.

Bob Stein
  • 16,271
  • 10
  • 88
  • 101
  • 1
    Could you not run the serializeArray and then lookup the elements by the names? Granted radio buttons would have to be filtered. Also you could start digging in the source to see what jQuery actually does to find the guys to include: https://j11y.io/jquery/#v=git&fn=jQuery.fn.serializeArray – Taplar Oct 12 '17 at 18:18
  • @Taplar, that ended up being an even more elaborate function. – Bob Stein Oct 12 '17 at 18:24
  • Could you share what you tried? – Taplar Oct 12 '17 at 18:25
  • @Taplar the only thing I tried that worked is above. And the question is already too wordy. But the core was `$submits2 = $submits2.add($('[name=' + $.escapeSelector(this.name) + ']'));`. Again, this translation of .seralizeArray() includes too much. Good tip on checking the source though. – Bob Stein Oct 12 '17 at 18:29
  • https://jsfiddle.net/91q7ovv5/ is the short dabble i came up with. I don't really like the pure attribute selectors, but meh – Taplar Oct 12 '17 at 18:31
  • What is expected result? – guest271314 Oct 12 '17 at 19:07
  • @guest271314 `$submittables` is the expected result, with an example usage in the last code snippet. It's a jQuery-collection of the elements that contribute the name-value pairs that would be submitted. – Bob Stein Oct 12 '17 at 20:23

0 Answers0