Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't click on label to select checkbox with Bootstrap checkbox layout

So I have the following code:

// the loop
                $countId = 0;
                $dateOnce = '';
                foreach ($postDates as $post):
                    if (substr($post->post_date, 0, 7) != $dateOnce) {
                        echo'
                            <div class="checkbox">
                                <label for="filterByPostDate-' . $countId . '">
                                    <input type="checkbox" id="filterByPostDate-' . substr($post->post_date, 0, 7) . '" class="postDateFilters postDateFilterCb-' . $countId . '" name="filterByPostDate-' . $countId . '" value="' . substr($post->post_date, 0, 7) . '" '; if (isset($_SESSION["filterByPostDate"])) { $key = array_search(substr($post->post_date, 0, 7), $_SESSION["filterByPostDate"]); } else { $key = false; } if($key !== false) { echo 'checked'; } echo ' />
                                    ' . date('M, Y', strtotime($post->date_part)) . '
                                </label>
                            </div>
                        ';
                    }
                    $dateOnce = substr($post->post_date, 0, 7);
                $countId++;
                endforeach;
                // END the loop

Which outputs checkboxes and labels for the wordpress frontend. But when I click on the label for each checkbox the checkbox doesn't get selected.

Here is a js fiddle which shows the problem.

Cheers for the help.

like image 438
Web Dev Guy Avatar asked Dec 03 '22 22:12

Web Dev Guy


2 Answers

you must include the id of your element in <label for="">

<div class="checkbox">
  <label for="filterByPostDate-2011-12">
    <input type="checkbox" id="filterByPostDate-2011-12" class="postDateFilters postDateFilterCb-0" name="filterByPostDate-0" value="2011-12"  />
    Dec, 2011
  </label>
</div>

<div class="checkbox">
  <label for="filterByPostDate-2012-01">
    <input type="checkbox" id="filterByPostDate-2012-01" class="postDateFilters postDateFilterCb-6" name="filterByPostDate-6" value="2012-01"  />
    Jan, 2012
  </label>
</div>
like image 192
Jeric Cruz Avatar answered Dec 08 '22 06:12

Jeric Cruz


You actually don't need the for attribute on your label at all, for the browser to let you click and select the checkbox . If you wrap your <label> tag around the input, then the browser knows that it is 'for' that field.

However, you should also include the for attribute, as not all assistive technologies recognise the relationship between label and input. As mentioned, the biggest issue with your code is that you are saying the label is 'for' something other than the input that it is wrapped around.

Here is an updated working fiddle https://jsfiddle.net/BrettEast/ffgL77qo/, using the correct for attribute.

like image 30
Brett East Avatar answered Dec 08 '22 06:12

Brett East