On post request, this code checks if the date input field given on a form contains today’s date. If so, the span
element placed next to the date input field must display an error message. My work is as following
$('.submit-btn').click(function() {
var d = new Date();
var month = d.getMonth();
var month_actual = month + 1;
if (month_actual < 10) {
month_actual = "0" + month_actual;
}
var day_val = d.getDate();
if (day_val < 10) {
day_val = "0" + day_val;
}
if ($('input[type="date"]').val() == d.getFullYear() + "-" + month_actual + "-" + day_val) {
var inputValue = $(this).attr("name");
$('.text-danger-' + inputValue).text("This date is incorrect");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input asp-for="@Model.DateOfBirth" class="form-control" type="date" name="inputDateOfBirth" />
<span class="text-danger-inputDateOfBirth"></span>
<button class="submit-btn">Submit</button>
span
is not showing the error-message text (This date is incorrect).
3
Answers
In this code
this
is pointing to thebutton
– which doesn’t have aname
– not theinput
(which you wanted).So
will actually be
which won’t find an element, thus it cannot set the text.
Had you not used jQuery you’d have found an error in the console helping you, namely
cannot access property "text" of null
.this
in the context where you used it was the button and it had no name. Fixed version:I am not entirely sure what you wanted to achieve with your snippet, but you used the wrong
this
inside your function, as it will point to the button element and not the input element with thevalue
inside. Your addressing mechanism involving thename
attribute and creating a class name out of it seems overly complicated. The snippet below addresses the elements n a relative way through the jQuery.prev()
method:(( The above snippet contains two groups of input and button elements to demonstrate the relative DOM element selection with
$(this).prev()
. ))