Home > OS >  I want to add an alert in the if else statement. How do I do that?
I want to add an alert in the if else statement. How do I do that?

Time:01-25

I want to add an alert inside the if and else if. If the user does not enter anything in the prompt box the alert triggers. Also if the user enters a number the prompt it will say that the user entered a number. How do do that?

let myForm2 = document.querySelector('.form2');
let pDisplay1 = document.querySelector('.display4');
myForm2.addEventListener('submit', function(e) {
  e.preventDefault();
  let uname = document.querySelector('.inputName2').value;
  if (uname == null) {


  } else if (isNaN(uname) == false) {

  } else {
    pDisplay1.innerHTML = `Welcome to the program ${uname}`;
  }

})
<p> Activity 6</p>
<form  method="get">
  <label>Full Name: <input type="text" ></label>
  <input type="submit">
</form>
<p ></p>

CodePudding user response:

document.querySelecte('.className').value will return a string.

string.trim() removes the whitespaces and if the length === 0 it means that the input is empty or has only whitespaces which you generally want to treat as empty. If you consider space is a valid input you don't have to use trim().

The sign will convert a string into a number otherwise you could use parseInt(variable).

Number.isInteger(variable) will return true if the variable is an integer.

You could also write !isNaN( uname) or uname !== Number.NaN

myForm2.addEventListener('submit', function (e) {
    e.preventDefault();
    let uname = document.querySelector('.inputName2').value;
    if (uname.trim().length === 0) {
        alert('You should write something');
    } else if (Number.isInteger( uname)) {
        alert('You wrote a number');
    } else {
        pDisplay1.innerHTML = `Welcome to the program ${uname}`;
    }
});

CodePudding user response:

Empty string is not equal to null, replace uname==null with uname=='', after the replacement, you can identify the situation that the user did not input, if it is more strict, you can also use trim to remove whitespace and then do condition review

  •  Tags:  
  • Related