-2

I have put this JavaScript code in file JavaScript.js:

var target = Number(prompt("Enter The New Number"));
function monthName(){
    var month = target == 1 ? month = "January" : target == 2 ? month = "February" : target == 3 ? month = "March" : target == 4 ? "April" : target == 5 ? "May" : target == 6 ? "June" : target == 7 ? "July" : target == 8 ? "August" : target == 9 ? "September" : target == 10 ? "October" : target == 11 ? "November" : target == 12 ? "December" : "Unknown Month";
    return month;
}
document.getElementById('yes').html= monthName();

And added a label with this particular id.

<label id="yes" ></label>
rene
  • 41,474
  • 78
  • 114
  • 152
Rajan Mishra
  • 1,178
  • 2
  • 14
  • 30

2 Answers2

3
  1. input check the number
  2. use an array if acceptable input
  3. assign to innerHTML (case sensitive)
  4. function can only run AFTER the label exists in the DOM
  5. note for the future that JS months are 0 based (not relevant here)

function monthName(month) {
  month = month.trim();
  if (isNaN(month) || month == "" || month < 0 || month > 12) return "unknown";
  return ["unknown", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][month];
}
// this needs to be after the label exists or wrapped in 
// window.onload=function() {...} or similar 
document.getElementById('yes').innerHTML = monthName(prompt("Enter The New Number", ""));
<label id="yes"></label>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

As pointed out by @epascarello, use .innerHTML instead of .html.

The Element.innerHTML property sets or gets the HTML syntax describing the element's descendants.

Read up: Element.innerHTML - Web APIs | MDN

Working snippet:

document.addEventListener("DOMContentLoaded", function(event) {

  var target = Number(prompt("Enter The New Number"));

  function monthName() {
    var month = target == 1 ? month = "January" : target == 2 ? month = "February" : target == 3 ? month = "March" : target == 4 ? "April" : target == 5 ? "May" : target == 6 ? "June" : target == 7 ? "July" : target == 8 ? "August" : target == 9 ? "September" : target == 10 ? "October" : target == 11 ? "November" : target == 12 ? "December" : "Unknown Month";
    return month;
  }

  document.getElementById('yes').innerHTML = monthName();

});
<label id="yes"></label>

In response to your comment, add your existing JavaScript code in the event listener of DOMContentLoaded with the fix of .innerHTML, just to make sure that it is executed after DOM content is loaded. Make sure that you use @mplungjan's JavaScript code inside of the DOMContentLoaded event handler since it is well written and better than mine.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138