1
votes

I have a form with multiple input fields where users may choose to enter a value or not. Next to each input field is a hidden input field that will send a specific id unique to the previous input field. On form submission, all blank input fields are disabled. This I got to work using this code.

function disableEmptyInputs(form) {
    var controls = form.elements;
    for (var i = 0, iLen = controls.length; i < iLen; i++) {
        controls[i].disabled = controls[i].value == '';
    }
}

I now want to also disable the hidden inputs if their primary visible input field is null

<div class="col-md-4">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input name="Pay" placeholder="Amount for A" class="form-control" type="text" />
<input type="hidden" name="PayId" value="A" />
</div>
</div>

<div class="col-md-4">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input name="Pay" placeholder="Amount for B" class="form-control" type="text" />
<input type="hidden" name="PayId" value="B" />
</div>
</div>

Any help will be really appreciated. The form submits to a c# backend where I am able to filter out all blanks If I allowed all blanks to be submitted but I felt if I could filter all blanks by making them disabled at the client side in addition to server side that will be better.

1
Hi, can you use jquery ? - Swati
Yes I can use jquery - Diin

1 Answers

0
votes

You can use .each loop to iterate through your form elements and then compare if the value of input is "" simply disable that input and also the input next to it using .next().

Demo Code :

$("form").on("submit", function() {
  //loop through input(exclude hidden input)..select..etc
  $("form").find("input:not(:hidden),select").each(function() {
    //if the value is empty
    if ($(this).val() == "") {
      $(this).prop("disabled", true) //disable
      $(this).next().prop("disabled", true) //also next field (hidden) disable
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div class="col-md-4">
    <div class="input-group mb-3">
      <div class="input-group-prepend">
        <span class="input-group-text">$</span>
      </div>
      <input name="Pay" placeholder="Amount for A" class="form-control" type="text" value="abc" />
      <input type="hidden" name="PayId" value="A" />
    </div>
  </div>

  <div class="col-md-4">
    <div class="input-group mb-3">
      <div class="input-group-prepend">
        <span class="input-group-text">$</span>
      </div>
      <input name="Pay" placeholder="Amount for B" class="form-control" type="text" />
      <input type="hidden" name="PayId" value="B" />
    </div>
  </div>
  <button>Click me ..</button>
</form>