Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox inputs badly aligned when there's no accompanying label using Bootstrap and MVC5

Bootply to play with

Visual Studio 2013 generates the following CSHTML when scaffolding an edit view for a model with a boolean:

<div class="form-group">
    @Html.LabelFor(model => model.IsUrgent, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="checkbox">
            @Html.EditorFor(model => model.IsUrgent)
         </div>
    </div>
</div>

After passing through Razor you get this:

<div class="form-group">
  <label class="control-label col-md-2" for="IsUrgent">Is bad :(</label>
   <div class="col-md-10">
    <div class="checkbox">
      <input class="check-box" data-val="true" id="IsUrgent" name="IsUrgent" type="checkbox" value="true">
      <input name="IsUrgent" type="hidden" value="false">
    </div>
  </div>
</div>

Twitter Bootstrap 3.2 however doesn't like this way of using labels because this is the result:

Screenshot

Note that the checkbox is positioned too much to the left.

If I wrap my input in a dummy label with some whitespace, ie.

<div class="form-group">
    <label class="control-label col-md-2" for="IsUrgent">Is good!</label>

    <div class="col-md-10">
      <div class="checkbox">
        <label><input class="check-box" data-val="true" id="IsUrgent" name="IsUrgent" type="checkbox" value="true">
        <input name="IsUrgent" type="hidden" value="false">&nbsp;</label>
      </div>
    </div>
</div>

I get this:

Second screenshot

which looks nice but it's not valid HTML:

The label element may contain at most one input, button, select, textarea, or keygen descendant.

Am I doing something wrong with my CSS classes?

Edit

If I move the second input outside of the label as @Saranga suggests I'm still left with the redundant label that serves no semantic function ...

like image 212
janv8000 Avatar asked Jul 15 '14 12:07

janv8000


2 Answers

<div class="checkbox">
    <label>
        @Html.CheckBoxFor(model => model.IsUrgent)
        @Html.DisplayNameFor(model => model.IsUrgent)
    </label>
</div>
like image 123
David Morissette Avatar answered Sep 18 '22 07:09

David Morissette


Instead of @Html.EditorFor(model => model.IsUrgent) add following code. You can put the hidden field outside the label tag.

<div class="checkbox">
    <label>
        <input class="check-box" data-val="true" id="IsUrgent" name="IsUrgent" value="true" type="checkbox"> &nbsp;
    </label>
    <input name="IsUrgent" type="hidden" value="false">
</div>

DEMO

Thanks!

like image 42
Saranga Avatar answered Sep 19 '22 07:09

Saranga