Levan Charuashvili
Levan Charuashvili

Reputation: 163

Making form with vanilla javascript

I want to make form with vanilla javascript. when id="text" value is nothing I meant space I want alert to pop, I'm makin' it with if statement but doesn't seem to work here's code

var input = document.getElementById('text');
function check(){
    if(input.value == " "){
        alert('hello');
    }
}
 Username: <input name="fname" type="text" onsubmit="check()" id="text" placeholder="Enter your username"> <br>
<button type="submit">asd</button>

Upvotes: 1

Views: 4366

Answers (2)

mplungjan
mplungjan

Reputation: 177885

  1. You need to get the field value every time the user clicks - if your initial code is not after the element, your code would fail, because document.getElementById('text'); will be undefined
  2. An input field does not have an onsubmit event
  3. I recommend to have a value attribute too and trim it before testing

You likely mean this

document.getElementById("form1").addEventListener("submit", function(e) {
  var input = document.getElementById('text');
  if (input.value.trim() === "") {
    alert('Please fill in user name');
    input.focus();
    e.preventDefault(); // stop form submission
  }
});
<form action="yourserverprocess" id="form1">
  Username: <input name="fname" type="text" 
             id="text" placeholder="Enter your username" value="" /><br />
  <button type="submit">Send</button>
</form>

Without a form

document.getElementById("subbut").addEventListener("click", function(e) {
  var input = document.getElementById('text'), val = input.value.trim();
  if (val === "") {
    alert('Please fill in user name');
    input.focus();
  }
  else {
    console.log("You typed",val);
  }
});
Username: <input name="fname" type="text" 
             id="text" placeholder="Enter your username" value="" /><br />
<button id="subbut" type="button">Send</button>

Upvotes: 6

Showrin Barua
Showrin Barua

Reputation: 1795

Here's the solution of your problem.
I've made some changes in your code.
1. you have to put onsubmit event in form tag. Because doesn't support onsubmit event. 2. Change the function name from check() to checkAlert(). May be check is a library keyword which causes your code to fail.

var input = document.getElementById('text');

function checkAlert() {
	if(input.value == ""){
    alert('hello');
  }
}
<form onsubmit = "checkAlert(this)">
   Username: <input name="fname" type="text" id="text" placeholder="Enter your username"> <br>
  <button type="submit">asd</button>
</form>

Upvotes: 1

Related Questions