0

I am using the .serializeArray function to gather all of the inputs of a form but I want to exclude inputs within a certain div class. I thought the .not() selector would do this but it does not appear to be working.

At its most basic level here is my code:

HTML:

<form class="theForm">
  <input name="a" value="a"/>
  <div class="excludeMe">
    <input name="c" value="c"/>
  </div>
</form>

Javascript:

$.each($(".theForm").not(".excludeMe").serializeArray(), 
function() {
    alert(this.name);
});

I would expect the alert to just be 'a' but this is alerting 'a' and then 'b'.

Fiddle: https://jsfiddle.net/cysaczu5/

Nate23VT
  • 423
  • 8
  • 27

5 Answers5

1

You have to wrap all inputs in <div><input/></div>

And then change the selector to this $.each($(".theForm :not(.excludeMe) input")

https://jsfiddle.net/cysaczu5/3/

I would recommend to remove the div and add the "excludeMe" class to the inputs directly. Then the selector becomes $.each($(".theForm input:not(.excludeMe)")

lipp
  • 5,586
  • 1
  • 21
  • 32
0

Well use this class on the inputs not divs and it will work.

'


 $.each($("input").not(".excludeMe").serializeArray(), 
   function() {
    alert(this.name);
});

'

<input name="c" class='excludeMe' value="c"/>

JSFidle

0

Please try

<form class="theForm">
<input name="a" value="a"/>
<div class="excludeMe">
  <input class="excludeMe" name="c" value="c"/>
</div>
</form>
$.each($(".theForm :not(.excludeMe)").serializeArray(), 
function() {
    alert(this.name);
});
maulik sakhare
  • 1,957
  • 1
  • 12
  • 19
  • There is no difference between your code and the OP's one.. you should add `input` before `:not` in order to make it work as it should – Mihai Matei Apr 21 '16 at 12:37
  • You need to add the input after the :not as @lipp suggested – Nate23VT Apr 21 '16 at 12:39
  • @MateiMihai - There is a difference I have added `class="excludeMe"` to input. As `"not(.excludeMe)"` will exclude form items having class `"excludeMe"` I have added it to input. Also `"input after the :not"` is not compulsory. View [JSfiddle](https://jsfiddle.net/1ouc79nm/3/) – maulik sakhare Apr 22 '16 at 09:24
0

The most simple answer would be to remove the name attribute from the inputs you want to skip. This way it is also skipped by serializeArray():

HTML:

<form class="theForm">
  <input name="a" value="a" />
  <input value="c" />
</form>

JS:

$.each($(".theForm").serializeArray(), function() {
    alert(this.name);
});
chrisg86
  • 11,548
  • 2
  • 16
  • 30
0

Simply put input before :not statement to match only the inputs inside the form, not the form itself:

$.each($(".theForm input:not(.excludeMe)").serializeArray(), function() {
    alert(this.name);
});

https://jsfiddle.net/cysaczu5/5/

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50