Unlocking button when the correct answer is filled in - javascript

So, I am making something where the user has to fill in their username and password in the beginning and in the end they can submit their score. I want the button to be disabled when the wrong data is filled in and to enable the button when the correct data is filled in. I cant get it to work. I have the name and password stored in the localStorage.
HTML
<button id="submit" class="register_button" type="submit" value="submit">Submit</button>
JavaScript
if (document.getElementById('name2') == localStorage.getItem('name') && document.getElementById('password2') == localStorage.getItem('password')) {
document.getElementById("submit").disabled = false;
} else {
document.getElementById("submit").disabled = true;
};

your expression is wrong you need to add .value after document.getElementById('name2') you are comparing the whole element not it's value
below is the working example
<input type="text" name="" id="name2">
<input type="text" name="" id="password2" onkeydown="validateData();">
<button id="submit" class="register_button" disabled type="submit" value="submit">Submit</button>
<script>
localStorage.setItem('name', "fazal")
localStorage.setItem('password', "pwd")
function validateData() {
//alert(document.getElementById('name2').value);
if (document.getElementById('name2').value == localStorage.getItem('name') && document.getElementById('password2').value == localStorage.getItem('password')) {
document.getElementById("submit").disabled = false;
} else {
document.getElementById("submit").disabled = true;
};
}
</script>

Related

How to disable button until input field has a value using AngularJS

I know nothing about Angular but I was asked to create a validation for the new google map input. All I want to do is have the #lugar_continuar button stay disabled until the input #ciudad is filled in, but the button isn't disabled for some reason.
index.php, input to validate
<div class="">
<input id="ciudad" name="ciudad" class="ciudad" type="text"
placeholder="Ciudad" value="" required ng-model="ciudadSet">
<div id="map"></div>
<input type="hidden" id="distance" size="31" value="31">
</div>
Input type button that should stay disabled
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && ciudadSet" ng-click="from_precio = true" >
Using ng-model doesn't work. I also tried with JS, in main.js:
var ReservasApp = angular.module('Reservas',['rzModule']);
ReservasApp.controller('ReservasController',function($scope){
$scope.ciudad = "";
$scope.validacionCiudad = function() {
var disabled = false;
if( $scope.ciudad != null && $scope.ciudad != "" )
{
disabled = false;
}
else
{
disabled = true;
}
}
}
index.php
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && validacionCiudad()" ng-click="from_precio = true" >
I also tried using only JS:
var validacionCiudad = function() {
var ciudad = document.getElementById('ciudad');
var btn = document.getElementById('lugar_continuar');
if (ciudad.value == "") {
btn.setAttribute("disabled", "disabled");
} else {
btn.removeAttribute("disabled");
}
}
validacionCiudad();
I have tried many ways to achieve this but nothing is working!
you can try this: ng-disabled = "ciudadSet == ''", since ng-disabled is valid when the expression equals true. If you must call function validacionCiudad to judge this, you have to return bool value in your function. May this will help.
Change $scope.ciudad ="" to $scope.ciudad = undefined;
change your ng-model to:
ng-model="ciudad"
and your ng-disabled to:
ng-disabled="!ciudad"
that shall work
You can validate it like this.
<div ng-controller="MyCtrl">
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<input name="name" ng-model="name" type="text" required >
<br>
<button type="submit" ng-disabled="userForm.$invalid" >Enviar</button>
</form>
</div>
https://jsfiddle.net/ivanm07/y2t88817/

disable and enabling a html button

Users will only be able to click the submit button if users select a video file and the textbox is not empty. i can disable the submit button but i cant re-enable it
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span></span></label>
<input type="file" name="videofile" id="videofile" />
<br/>
Please enter video title:
<br/>
<input type"text" name="videoTitle" />
<br />
<input type="button" disabled id="Submit" value="Submit" onclick="submit()"/>
</form>
<script>
document.getElementById('submit').disabled = true;
var n=document.getElementById('videoTitle').value;
function submit();
if($('#videofile')[0].files.length != 0) && (n.length > 1)
{
document.getElementById('submit').disabled = false;
}
</script>
Your code had a lot of mistakes. This is your corrected code:
function check() {
if (document.querySelector('#videofile').files.length != 0 && (document.getElementById("videoTitle").value.length > 1)) {
document.getElementById('Submit').disabled = false;
} else {
document.getElementById('Submit').disabled = true;
}
}
Here is the JSFiddle demo
Missing ID added (u added only name attribute, and forgot the ID while still trying to use them)
Changed 'submit' in code to 'Submit'
Remove JQuery $ syntax
Validation on keypress rather than on submit click (which doesn't makes sense since u cant click the button while its disabled)
Else code added to re-disable the button if conditions are not valid
onclick event over submit button does not make sense here. You must listen change event of the file input and keyup event of the text input and apply conditions accordingly. You have not assigned id attribute as well(videoTitle)
Also note that click handler will not be invoked if the button is disabled
Try this:
var submitBtn = document.getElementById('Submit');
function enableDisable() {
var elem = document.getElementById('videofile');
var n = document.getElementById('videoTitle').value;
if (elem.files.length && n) {
submitBtn.disabled = false;
} else {
submitBtn.disabled = true;
}
}
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span></span></label>
<input type="file" name="videofile" id="videofile" onchange='enableDisable()' />
<br/> Please enter video title:
<br/>
<input type="text" name="videoTitle" id='videoTitle' onkeyup='enableDisable()' />
<br />
<input type="button" disabled id="Submit" value="Submit" />
</form>
Can you try to make your submit function do something?
function submit() {
if($('#videofile')[0].files.length != 0) && (n.length > 1) {
document.getElementById('submit').disabled = false;
}
};
you should use change event for text and videofile elements. So that whenever you modify something, change event is triggered and ur condition is checked inside it. Submit button is enable according to it.
Se the below code for reference!
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span></span></label>
<input type="file" name="videofile" id="videofile" />
<br/>
Please enter video title:
<br/>
<input type"text" name="videoTitle" id="videoText"/>
<br />
<input type="button" disabled id="Submit" value="Submit" onclick="submit()"/>
</form>
<script>
document.getElementById('submit').disabled = true;
var n=document.getElementById('videoTitle').value;
function submit();
$('#videofile').change(function() {
if($('#videofile')[0].files.length != 0) && (n.length > 1) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
});
$('#videoText').change(function() {
if($('#videofile')[0].files.length != 0) && (n.length > 1) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
});
</script>
I feel this is a bit simpler way to achieve this
<script>
document.getElementById("submit").style.pointerEvents = "none"; //Disable
var n=document.getElementById('videoTitle').value;
function submit();
if($('#videofile')[0].files.length != 0) && (n.length > 1)
{
document.getElementById("submit").style.pointerEvents = "all"; //Enable
}
</script>
Just replace your script with this one & try..
Hope this works for you..

Validating form after error has been shown

I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}

Form Send Button Will Not Validate Form Input Text Fields When Asked to Continue Form Submit

I have a form on my webpage at www.thetotempole.ca and for example it has a postal/zip code text field and if the user does not type in a correct zip/postal code the form will display a popup saying that the zip/postal code is not valid. Although, when the user hits submit I want it to display a confirm pop up asking if they really want to send the form. This interferes with the input text field validations (I.E the zip postal code validator) some how and ends up not validating the text fields at all. Any help is appreciated. Thank you!!
HTML:
<html>
<head>
<script>
function validate()
{
var myform = document.getElementById("form1");
myform.fname.style.backgroundColor = "white";
myform.lname.style.backgroundColor = "white";
myform.address.style.backgroundColor = "white";
myform.city.style.backgroundColor = "white";
myform.provstate.style.backgroundColor = "white";
myform.country.style.backgroundColor = "white";
myform.postalzip.style.backgroundColor = "white";
console.log("form object: " + myform);
if (myform.fname.value == "")
{
alert("First Name must have a value");
myform.fname.focus();
myform.fname.style.backgroundColor = "red";
return false;
}
if (myform.lname.value == "")
{
alert("Last Name must have a value");
myform.lname.focus();
return false;
}
if (myform.address.value == "")
{
alert("Address must have a value");
myform.address.focus();
return false;
}
if (myform.postalzip.value == "")
{
alert("Postal/Zip Code must have a value");
myform.postalzip.focus();
return false;
}
else
{
//var regex = new RegExp();
var regex = /^([a-z]\d[a-z]\s?\d[a-z]\d)|(\d{5}(\s?\d{4})?)$/i;
myform.postalzip.value.toUpperCase();
if (!regex.test(myform.postalzip.value))
{
alert("Postal/Zip Code has invalid format");
myform.postalzip.focus();
return false;
}
}
return true;
}
</script>
</head>
<body>
<form id="form1">
First Name:<input type="text" name="fname" /><br />
Last Name:<input type="text" name="lname" /><br />
Address:<input type="text" name="address" /><br />
City:<input type="text" name="city" /><br />
Province/State:<input type="text" name="provstate" /><br />
Country:<input type="text" name="country" /><br />
Postal/Zip Code:<input style="text-transform: uppercase;" type="text" name="postalzip" /><br />
<input type="submit" onclick="return confirm('Do you really want to continue?')" value="Send" />
<input type="reset" onclick="return confirm('Do you really want to reset?')" value="Reset" />
</form>
</body>
</html>
A quick-fix:
<input type="submit" onclick="return (validate() && confirm('Do you really want to continue?'))" value="Send" />

Validation through getElementById()

I'm been trying to validate my fields by using 'getElementById()' with '.value'. However, it seems like either getElementById.value is not working or some codes has overlap the function.
Updated Javascript function:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("Don leave blank!")
return false;
}
if (isNaN(Tel)) //check only numbers. Same code for FaxNo.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("invalid");
return false
}
return true; //doesn't go to next.php
}
My Form:
<Form action ="next.php" method="post">
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
<input type="submit" name="submit" onclick="return validate();"/>
</Form>
I have already defined my onclick function to my Javascript and tried to add return false too. But the alert still cant appear. Kindly advise.
Your markup is invalid:
<input name="Name" type="text" id="Name" " value=""/>
^-----------should be removed
so correction would be removing all extra " characters:
<input name="Name" type="text" id="Name" value=""/>
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
For preventing submition,when input is invalid, you can try something like a:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
alert("Correct")
else {
alert("Don leave blank!")
return false;
}
if (isNumeric(Tel)) //check only numbers. Same code for FaxNo.
alert("Correct")
else {
alert("invalid");
return false;
}
}
//Borrowed from jQuery lib
function isNumeric( obj ){
return !isNaN( parseFloat(obj) ) && isFinite( obj )
}
<input type="submit" name="submit" onclick="return validate()"/>
Try this,
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") {}
else {alert("Don leave blank!"); return false;}
if (isNaN(Tel)){ alert("invalid"); return false;}
else { }
return true;
}
Your HTML submit button code should be
<input type="submit" name="submit" onclick="return validate()"/>
Use return false to prevent submitting form in case of any validation errors.

Categories

Resources