Displaying alerts based on user's checkbox selection

Is following a correct way to check for empty input and then handle it:

The function gets called when a button is pressed and there is a input text field with id tag and I am trying to check if that field is empty and then display a message to the user. When I didn’t put anything in the input field, I was able to see these alerts alert("Primary Instance is selected");, and the other two alert(isTagEmpty); one of which is above the isTagEmpty.trim(); and one is below it but for some reason I didn’t see this one alert("tag # is required because you have selected Primary Instance Affiliation"); and hence wanted to check if I’m doing it correctly or not. Thanks

function affiliationchecks()

var isFirstInstanceSelected = document.getElementById("affiliatedPrimary5").checked;
var isSecondInstanceSelected = document.getElementById("affiliatedSecondary5").checked;

  if (isFirstInstanceSelected) {
    alert("Primary Instance is selected");
    //check if tag is empty or not
    let isTagEmpty = document.getElementById("tag").value;
    if (isTagEmpty == "") {
      alert("tag # is required because you have selected Primary Instance Affiliation");

  if (isSecondInstanceSelected)
   alert("SECONDARY Instance selected");

Have you ever tried to check the content of isTagEmpty within the console?


My guess is, that it is null and not an empty string

I would always test on an empty field by using


It printed as <empty string> in the console log. Are you saying I should use isFirstInstanceSelected.value ?trim().length instead of the above quoted if statement?

Instead of

if (isTagEmpty == "") {.....}


if (!isTagEmpty) {.....}

That detects any falsey value

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.