Firefox v57.0.1 supports the attribute “date” for the HTML input tag.
I would like in jQuery to reset the date value when the user click on a radio button like this:
In order to get this result:
My jQuery code:
JavaScript
x
10
10
1
$("input[name=f_foo_duration]").click(function() {
2
3
if ($("#f_foo_duration_until").is(':checked')) {
4
$("#f_foo_duration_date").attr("readonly", false);
5
}else{
6
$("#f_foo_duration_date").attr("readonly", true);
7
$("#f_foo_duration_date").attr( "value", new Date() ); <-- here
8
}
9
});
10
I tested:
- val(“”)
- val(null)
- val(“0000-00-00”)
- val( new Date() )
without any success… is there a solution?
Advertisement
Answer
To set an input element’s value use the jQuery function elem.val("...")
:
JavaScript
1
12
12
1
$(function() {
2
$('[name="contact"]:radio').on("change", function() {
3
if ($("#f_foo_duration_until").is(":checked")) {
4
let now = new Date().toISOString().slice(0,10);
5
$("#f_foo_duration_date").val(now);
6
$("#f_foo_duration_date").attr("readonly", false);
7
} else {
8
$("#f_foo_duration_date").val("YYYY-MM-DD");
9
$("#f_foo_duration_date").attr("readonly", true);
10
}
11
});
12
});
JavaScript
1
3
1
#my-form > * {
2
vertical-align: middle;
3
}
JavaScript
1
13
13
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2
<form id="my-form">
3
4
<input type="radio" id="f_foo_duration_until" name="contact" value="email">
5
<label for="f_foo_duration_until">Valid until</label>
6
7
<input id="f_foo_duration_date" name="f_foo_duration" type="date" value="2017-06-01">
8
</input>
9
10
<input type="radio" id="f_foo_duration_unlimited" name="contact" value="unlimited">
11
<label for="f_foo_duration_unlimited">Unlimited</label>
12
13
</form>