Reputation: 163
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
Reputation: 177885
document.getElementById('text');
will be undefinedYou 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
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