inputbox change value event looks like not firing in asp.net razor bounded with bootstrap datetimepicker with eonasdan-bootstrap-datetimepicker

Viewed 38

I have a textbox bound with datetime picker. What I have to do is on change of value in the text box if another input textbox (which also bound with datetimepicker) is empty I have to fill the value from initial textbox.

I am trying following but no alert coming:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
  $(document)
    .off("change", "#FirstDate")
    .on("change", "#FirstDate", function(e) {
      e.preventDefault();
      console.log($(this).val());
    });
</script>

<div class="form-group">
  <label>First Date</label>
  <div class="input-group date">
    <input id="FirstDate" name="FirstDate" type="text" class="form-control" asp-for="FirstDate" />
    <span class="input-group-addon"></span>
  </div>
  <span asp-validation-for="FirstDate" class="error"></span>
</div>

<div class="form-group">
  <label>Second Date</label>
  <div class="input-group date">
    <input id="SecondDate" name="SecondDate" type="text" class="form-control" asp-for="SecondDate" />
    <span class="input-group-addon"></span>
  </div>
  <span asp-validation-for="SecondDate" class="error"></span>
</div>

1 Answers

You should always run the script only when it knows what to refer to. The script part, is executed syncronous and has to come after the divs or needs a trigger where the elements are present at the dom. If it is executed straight at this point, jquery won't find the elements and can't add the listener.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<div class="form-group">
  <label>First Date</label>
  <div class="input-group date">
    <input id="FirstDate" name="FirstDate" type="text" class="form-control" asp-for="FirstDate" />
    <span class="input-group-addon"></span>
  </div>
  <span asp-validation-for="FirstDate" class="error"></span>
</div>

<div class="form-group">
  <label>Second Date</label>
  <div class="input-group date">
    <input id="SecondDate" name="SecondDate" type="text" class="form-control" asp-for="SecondDate" />
    <span class="input-group-addon"></span>
  </div>
  <span asp-validation-for="SecondDate" class="error"></span>
</div>



<script>
  $(document)
    .off("change", "#FirstDate")
    .on("change", "#FirstDate", function(e) {
      e.preventDefault();
      console.log($(this).val());
    });
</script>

Related