Search code examples
javascriptjqueryserializearray

jQuery SerializeArray and Not selector


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/


Solution

  • 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)")