Created
November 15, 2013 20:40
-
-
Save samchrisinger/7491189 to your computer and use it in GitHub Desktop.
jQuery form serialize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('#submit').on('click', function(e){ | |
e.preventDefault(); //IMPORTANT-- you must stop the form from automatically sending a POST request | |
var obs = $('#observer_form').serializeArray(); | |
var met = $('#metrics_form').serializeArray(); | |
var site = $('#site_form').serializeArray() | |
}); | |
// This returns three arrays of objects like {name:NAME, value:VALUE}. This is grabbing the HTML name attribute of the form contents as well at their values. I've added check boxes next to my <input> tags so blank fields don't get submitted. This looks something like: | |
$('.toggle').on('change', function(){ | |
// The this keyword corresponds to the element from which the event originated | |
// closest() navigates up the DOM until it finds an element that matches the selector (in this case .row) | |
// children() gives all of the children of that DOM node (now .row), and is optionally filtered by a selector (here that is .col2). Then calling children with the 'input' selector returns all inputs that are children of .col2. | |
var inp = $(this).closest('.row').children('.col2').children('input'); | |
// Setting the element to 'disabled' will stop if from being submitted with the form. | |
inp.attr('disabled', !inp.attr('disabled')); | |
// And clear the <input> value | |
inp.val(''); | |
}); | |
// My inputs look something like: | |
<div class="row"> | |
<div class="col1"><input type="checkbox" class="toggle"><label>LABEL</label></div> | |
<div class="col2"><input name="NAME"></div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment