Mihail Ivanchev Mihail Ivanchev - 2 months ago 8
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:

Javascript

$('body').on('click', '.saveStates', function () {
$('.states_list').each(function (key, value) {
forms.push($(this).serialize());
});


HTML

<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']; ?>">
</form>
<button type="button" class="saveStates btn btn-success">Save</button>


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

$('.states_list').each(function (key, value) {
if($('.selected_state').val()){
forms.push($(this).serialize());
}
});


But that does not work.
Any help is welcome.

Answer

You could filter it using .has():

$('body').on('click', '.saveStates', function() {
  $('.states_list').has('.selected_state:checked').each(function(key, value) {
    forms.push($(this).serialize());
  });
});

But you code could just be:

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