Mihail Ivanchev Mihail Ivanchev - 11 months ago 48
HTML Question

Serialize form data of a certain form out ot many, if a certain field has value jQuery

I have a page with a couple of forms (number is different, as they are loaded dynamically). I am able to cycle through every form on the page and serialize its data to send to my server. I was wondering if it's possible to only serialize/add data to the array only if a checkbox in any given form is ticked (and that gives it a value I need to use)?
Here is my code:


$('body').on('click', '.saveStates', function () {
$('.states_list').each(function (key, value) {


<form class="states_list">
<input type="checkbox" class="selected_state" name="active_state" value="<?php echo $state['id']; ?>"
<input type="text" class="col-md-10" name="pdf_price" id="pdf_price" value="<?php echo $state['pdf_price']; ?>">
<button type="button" class="saveStates btn btn-success">Save</button>

I need to check if the checkbox with class
has a value (is ticked), and then add that form to the
array. I was thinking of doing something like this:

$('.states_list').each(function (key, value) {

But that does not work.
Any help is welcome.

Answer Source

You could filter it using .has():

$('body').on('click', '.saveStates', function() {
  $('.states_list').has('.selected_state:checked').each(function(key, value) {

But you code could just be:

$('body').on('click', '.saveStates', function() {
  var forms = $('.states_list').has('.selected_state:checked').serializeArray();