1

I have a function that needs to loop through all the select tags and the cheackboxes, take their name and value and then assign it to the "data" object. Here's the code

data_query:->      
  data = {}
  $('input[type="checkbox"]').each ->
    data[$(this).attr('name')] = $(this).is(":checked")
  $('select').each ->
    data[$(this).attr('name')] = $(this).val()
  # console.log data
  return data

Result should be something like:

Object {select_one: "value", select_two: "value", ag_1: false, ag_2: true, ft_1: false, ft_2: false, bg_1: false}

But What I get at the end is:

Object {select_one: "value", select_two: "value", ag_1: false} #it gets only one checkbox

I understand the nature of callbacks and I know why it happens - the outer funcion ends before the end of the inner loops but I have no idea how to solve this

Thanks!

Edit: here is the HTML. Its just simple select tags and checkboxes

      <li><label for="ag_1"><input name="ag_1" type="checkbox" id="ag_1"> AG-1</label></li>
      <li><label for="ag_2"><input name="ag_2" type="checkbox" id="ag_2"> AG-2</label></li>
      <li><label for="ft_1"><input name="ft_1" type="checkbox" id="ft_1"> FT-1</label></li>
      <li><label for="ft_2"><input name="ft_2" type="checkbox" id="ft_2"> FT-2</label></li>
      <li><label for="bg_2"><input name="bg_1" type="checkbox" id="bg_2"> BG-1</label>    </li>

<!-- there's a bunch of these -->
<select name="select_one" id="select_one">
      <option value="">-- Select One --</option>
      <option value="ac_1">AC-1</option>
      <option value="ac_2">AC-2</option>
      <option value="ac_3">AC-3</option>
      <option value="ac_4">AC-4</option>
      <option value="ac_5">AC-5</option>
      <option value="ac_6">AC-6</option>
      <option value="ac_7">AC-7</option>
</select> 
DanielRavina
  • 95
  • 2
  • 6

1 Answers1

2

The problem is that CoffeeScript implictly returns the value you're assigning to the data property. Yet, the jQuery each does consider a return value of false as a break, and ends the loop. You have to return undefined "explicitly":

data = {}
console.log $('input[type="checkbox"]').each ->
  data[$(this).attr('name')] = $(this).is(":checked")
  return
$('select').each ->
  data[$(this).attr('name')] = $(this).val()
  return
return data

(Demo at jsfiddle.org, produced code)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375