I tried to do a simple validation on a button, but when I click the button without entering anything it still goes to testValidation1.html instead of popping up the alert window.
<html>
<head>
</head>
<body>
<form action="testValidation1.html">
Parameter1 :
<input type = 'text' name = 'param1'/><br>
<input type='submit' value = 'submit' onclick = 'return validateForm()'>
</form>
<script type="text/javascript">
function validateForm() {
var f1 = document.forms[0];
var p1 = f1.param1;
if(p1.value.length == 0) {
alert('Plz enter parameters');
p1.focus();
return false;
}
}
</script>
</body>
</html>
you might find it easier to use the submit event of the form to validate
function validateForm(event) {
var form = this;
var p1 = form.elements['param1'];
if(p1.value.length === 0) {
alert('Plz enter parameters');
p1.focus();
event.preventDefault();
return false;
}
}
document.getElementById('form').addEventListener('submit', validateForm);
http://jsfiddle.net/7j0usuam/
Related
Pressing the enter button on the keyboard, the HTML button (id="botonCorregir") should be pressed automatically, but does nothing.
HTML:
<form id="theFormID" class="text-center">
<input autofocus id="respuestaUsuario" type="text">
<button id="botonCorregir" onclick="corregir()">Responder</button>
</form>
JAVASCRIPT:
<script>
//This should push the html button
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
</script>
<script>
//This corrects the user answer
function corregir(){
var respUs = document.getElementById('respuestaUsuario').value;
var respUs=respUs.toLowerCase();
var respuestasDj = document.getElementsByClassName("idRespuesta");
var cantidad = respuestasDj.length;
var resultado = "incorrecto";
for(i = 0; i < cantidad; i++){
var respPosible = document.getElementsByClassName("idRespuesta")[i].getAttribute('value');
if(respUs == respPosible){
var resultado = "correcto";
}
}
}
</script>
For example if y try that, and push enter, doesn´t show alert "hello!". Why?
<script>
if (event.keyCode == 13) {
alert("hello!");
}
</script>
The usual way to do it in html/js is this one:
HTML
<form id="my-form">
<!-- creating a form, we use the on-submit event -->
<input type="text" autofocus id="respuestaUsuario" />
<button type="submit">Responder</button>
</form>
JS
// submit event runs when the user click the submit button or press enter on the input-text
document.getElementById('my-form').addEventListner('submit', evt => {
evt.preventDefault();
corregir();
});
Let me know if it's not clear enough and I'll try to explain it better.
the keyup event listener is for when you release the enter key
plus you can call the corregir function directly instead of triggering a click on the button
try :
<script>
//This should push the html button
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
corregir();
}
});
//This corrects the user answer
function corregir(){
var respUs = document.getElementById('respuestaUsuario').value;
var respUs=respUs.toLowerCase();
var respuestasDj = document.getElementsByClassName("idRespuesta");
var cantidad = respuestasDj.length;
var resultado = "incorrecto";
for(i = 0; i < cantidad; i++){
var respPosible = document.getElementsByClassName("idRespuesta")[i].getAttribute('value');
if(respUs == respPosible){
var resultado = "correcto";
}
}
}
</script>
also, a submit would be more addapted to this situation since the submit triggers itself on enter if an element of it's form is selected
Try to call the function direktly without clicking the button.
if (event.keyCode == 13) {
event.preventDefault();
corregir();
}
I want to enable my button, when input is filled. I want to do it in pure Javascript.
My code example in HTML:
<form action="sent.php" method="post" name="frm">
<input type="text" name="name_input" id="name" onkeyup="myFunction()"><br>
<button type="submit" class="button button-dark" id="send">Send message</button>
</form>
And Javascript:
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('send').disabled = "true";
function myFunction() {
var nameInput = document.getElementById('name').value;
if (!nameInput === "") {
document.getElementById('send').disabled = "false";
}
}
});
I don't know why my button is not changing to enable state after filling something in input. I have tried diffrent ways to do it, but it's still not working.
Please help.
An input element in HTML is enabled only when the disabled attribute is not present.
In your case disabled is always present in your element, it's just that it has a "false" or a "true" value - but this is meaningless according to the specs (http://www.w3schools.com/tags/att_input_disabled.asp)
So you need to remove it altogether:
document.getElementById('send').removeAttribute('disabled')
The problem with your code is that myFunction() isn't available because you defined it in the eventlistener for click.
Complete refactored code answer:
HTML
<form action="sent.php" method="post" name="frm">
<input type="text" name="name_input" id="name">
<br>
<button type="submit" class="button button-dark" id="send" disabled>Send message</button>
</form>
JS
document.getElementById("name").addEventListener("keyup", function() {
var nameInput = document.getElementById('name').value;
if (nameInput != "") {
document.getElementById('send').removeAttribute("disabled");
} else {
document.getElementById('send').setAttribute("disabled", null);
}
});
Try this one it will work for you
function myFunction() {
document.getElementById('send').disabled = true;
var nameInput = document.getElementById('name').value;
if (nameInput != "") {
alert("Empty");
document.getElementById('send').disabled = false;
}
}
if you want to check the input should not be contain number then we can use isNaN() function, it will return true if number is not number otherwise return false
Your code is almost correct but you have defined myFunction inside a block, so input is not able to find myFunction() inside onkeyup="myFunction()"
so just keep the same outside of DOMContentLoaded event
see working demo
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('send').disabled = "true";
});
function myFunction() {
var nameInput = document.getElementById('name').value;
console.log(nameInput);
if (nameInput === "") {
document.getElementById('send').disabled = true;
} else {
document.getElementById('send').disabled = false;
}
}
I have a form which validates password null/blank or not using onblur. And I use a submit button to submit the form. However the submit button needs to be clicked twice before to work. It does not work on the first click after something has been filled in the password box. Below is the code.
With respect to Jquery, I require solution in pure Javascript.
I have tried onkeyup, but that is not a good solution as it will put strain on system, and server (for ajax).
<!DOCTYPE html>
<html>
<body>
<script>
var error_user_password = false;
function checkpw(){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall() {
checkpw()
if(error_user_password == false) {
return false;
} else {
return true
}
}
</script>
</body>
<form id="joinform" method="post" name="joinform" action="#hello" onsubmit="return submitall()" >
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password" onblur="checkpw()" />
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
</html>
OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript
This happens because the blur event is captured from the onblur event handler and not bubbled to the form submit button.
A full javaScript solution is based on:
addEventListener
activeElement: inside the blur event I check after 10 milliseconds if the submit button get the focus.
My snippet:
var error_user_password = false;
function checkpw(ele, e){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_password == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_password').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
I already checked How to prevent form from being submitted? but it did not help.
I have a register form with some input and a submit button
<script src="formValidation.js"></script>
<script src="md5.js"></script>
<script language="javascript">
function doSomething() {
str = document.registration.userpass.value;
str2 = document.registration.userpass2.value;
document.registration.response.value = MD5(str);
document.registration.response2.value = MD5(str2);
document.registration.userpass.value="";
document.registration.userpass2.value="";
formValidation();}
<form name="registration" action="/Arnito_test/Register" method="post" >
<input onClick="return doSomething();" type=submit>
formValidation.js:
function formValidation() {
...
if (registration.userpass.value == registration.username.value) {
alert("Error: Password must be different from Username!");
document.registration.userpass.focus();
return false;
}
...}
If I force this alert, it appears, but the form submits anyway.
the return false should block it, no?
doSomething() needs a return statement. The last line should be:
return formValidation();
Try -
Add "event" as a parameter that doSomething gets
Send it to formValidation
Add event.preventDefault();
function doSomething(event)
{
str = document.registration.userpass.value;
str2 = document.registration.userpass2.value;
document.registration.response.value = MD5(str);
document.registration.response2.value = MD5(str2);
document.registration.userpass.value="";
document.registration.userpass2.value="";
formValidation(event);
}
function formValidation(event) {
if (registration.userpass.value == registration.username.value) {
alert("Error: Password must be different from Username!");
document.registration.userpass.focus();
event.preventDefault();
return false;
}
}
I think you should use
<input onSubmit="return doSomething();" type=submit>
I need to disable the submit button when the required fields are not filled. But the script is not working. If anybody can help, thanks in advance.
Html :
<input type="submit" value="Submit" name="sub1" id="submit1">
Javascript :
<script language="JavaScript">
function form_valid() {
var u1=document.getElementById("#user1").value;
var p1=document.getElementById("#pass1").value;
var p2=document.getElementById("#pass2").value;
var s1=document.getElementById("#school1").value;
if ((u1 == null)&&(p1 != p2)&&(s1 == null))
{
document.getElementById("#submit1").disabled = true;
document.getElementById("#submit1").setAttribute("disabled","disabled");
}
else
{
document.getElementById("#submit1").disabled = false;
document.getElementById("#submit1").removeAttribute("disabled");
}
}
function form_run() {
window.setInterval(function(){form_valid();}, 1000);
}
</script>
Body tag (HTML) :
<body bgcolor="#d6ebff" onload="form_run();">
var u1=document.getElementById("#user1").value;
Dont use #, you have many times in your code
var u1=document.getElementById("user1").value;