0

I have a (unchangable) form structure like this:

<div class="form-group">
    <div class="col-sm-3 control-label">
        <label for="frm-registrationForm-form-surname">Surname:</label>
    </div>
    <div class="col-sm-9">
        <input class="form-control text" id="registration-form-surname" type="text" name="surname" required>
    </div>
</div>

Is there possible to add the asterisk * sign next to all the labels relying to the inputs with "required" attribute using the CSS? I did not find any option to link the input with the label in CSS even in the same form group.

Thanks.

Lunack
  • 343
  • 1
  • 5
  • 14
  • Not possible with pure CSS – Gerard Aug 09 '17 at 13:49
  • If you want a CSS-only solution, that is not possible because (1) this requires traversing **up** the DOM tree, which is not supported in CSS (maybe in CSS4), but (2) this requires traversing **to a previous sibling**, which is for the same reason not supported. – Terry Aug 09 '17 at 13:50

2 Answers2

1

Using jQuery.

First solution. If .form-group has only one input and label elements.

$(document).ready(function () {
  $('input[required]').parents('.form-group').find('label').append('*');
});

Second solution. Working only of your label for and input id attributes the same

$(document).ready(function () {
  $("input[required]").each(function(index) {
    var id = $(this).attr('id');
    $('label[for="'+id+'"]').append('*');
  });
});

I would recommend you to use the second solution.

Dmitry B.
  • 426
  • 4
  • 11
0

You can use jQuery to implement this functionality. Inside document.ready function,

  var str ='*';
  $(".control-label").append(str);

Entire script would be

$(document).ready(function () {
  var str ='*';
  $(".control-label").append(str);
});
Alan Pallath
  • 99
  • 3
  • 14