Home > Mobile >  JQuery text function isn't showing the text
JQuery text function isn't showing the text

Time:11-01

I am using JQuery on laravel 8 and I am trying to show "This field is required." when the date field becomes empty. However, when I remove the default value (todays date) nothing shows. If I put the date in the future, "The date can't be in the future." shows no bother. I can't find out why. It is entering the "if (value === "")"

jquery

$(document).on("change", "#date", function(){
var value = $("#date").val();
if (value === ""){

  //this line doesn't show anything
  $("#dateError").text("This field is required.").css('color', '#ff0000').attr('class', 'col-6');
} else{
  $("#dateError").text("");
}
let today = new Date();
let inputDate = new Date(value);
if (inputDate > today){

// this will show
   $("#dateError").text("The date can't be in the future.").css('color', '#ff0000').attr('class', 'col-6');
} else{
   $("#dateError").text("");
}
})

html

<div class="row m-3">
  <label for="date" class="col-lg-2 me-2">Date<i>*</i></label>
  <input type="date" id="date" name="date" value="{{ old('date', now()->toDateString()) }}" class="col-lg-9"/>
</div>
<div class="row m-3">
  <span id="dateError"></span>
</div>

CodePudding user response:

The basic problem is you are running the second if() regardless of what happens in the first and the second will overwrite text set in the first.

One fix would be to return when value is empty and after the error text has been set

if (value === ""){
  
  $("#dateError").text("This field is required.").css('color', '#ff0000').attr('class', 'col-6');

   // don't go any further 
   return;
} else ...

CodePudding user response:

Maybe because of ===. Value is a date object, and you are comparing it to a string. And for the today variable, you created an instance only.

  • Related