Reputation: 221
Radio button is returning undefined value. my html code is :
<input name="start" value="" id="start1" type="radio">
<label for="start1">date</label>
javascript:
<script type="text/javascript">
(function() {
if (document.getElementById('start1').checked) {
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + 1);
}
});
</script>
when i check radio button start1 , then it will add 1 month to the current month. but my console.log(CurrentDate) shows undefined variable name. how can i show the result?
Upvotes: 2
Views: 859
Reputation: 312
This will work for you.
Simple JavaScript -
function check() {
if (document.getElementById('start1').checked) {
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + 1);
document.getElementById("dateDisplay").innerHTML = ""+CurrentDate;
}
};
<input name="start" value="" id="start1" type="radio" oninput="check()">
<div id="dateDisplay"></div>
Upvotes: 1
Reputation: 451
What you have is an immediately-invoked function expression which runs as soon as it is defined - so it's going to run before you even have a chance to click on the radio button.
You need to attach an event listener to your radio button so that your function runs when the radio is clicked (or changed) instead.
Upvotes: 1
Reputation: 8108
You did not call the wrapper function
(function () {
document.getElementById('start1').addEventListener('change', () => {
let CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + 1);
dateEl.innerHTML = CurrentDate
})
})();
<input name="start" value="" id="start1" type="radio">
<label for="start1">date</label>
<div id="dateEl"></div>
Upvotes: 1