lundi 6 janvier 2020

Best practice for conditional form elements with database unique ID reliance

I am working on a form with a number of conditional fields, which are hidden or revealed depending on check boxes, which themselves come from items in a table.

The checkboxes look like this

@foreach ($media as $medium)
        <div class="col-4 col-md-auto form-check form-check-inline media-checkbox-group required">
            <input class="form-check-input media-checkboxes" type="checkbox" name="media[]" value="" id="mediumId">
            <label class="form-check-label" for=""></label>
        </div>
@endforeach

my javascript function like this

$('#mediumId3').on("change", function () {
  var x = document.getElementById("block");
  if (this.checked) {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
});

and my html form element like this

<div id="block" style="display:none;">
  <div class="form-group row">
    <label for="poemCount" class="col-md-4 col-form-label text-md-right"></label>

    <div class="col-md-8">

      <div class="form-check form-check-inline">
        <label class="mr-1" for="countMin"></label>
        <select class="form-control" id="countMin" name="countMin">
          <option value=""> -- </option>
          @foreach ($numbers as $number)
            <option value="" ></option>
          @endforeach
        </select>
      </div>

    </div>

  </div>
</div>

Everything works fine and the element toggles on and off display as expected, but my question is this.

I'm worried that since the javascript relies on the medium unique id being '3', if this is ever changed (perhaps by an accidental deletion and replacement), the form will stop working. Is it ok to rely on database IDs for this sort of function? Is there a more robust way of doing it?

Thanks, Dan



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire