Is it possible to check the form field values dynamically with javascript only.
For example if I have form field for username and when the user enters their chosen username it checks whether this username is available and pops up an alert box or shows a message on the screen based on the result.
all of this is done without clicking any button. and the data is stored in an array.
Thanks in advance. Im trying to achieve this only by using javascript.
var username = document.getElementById('username');
var goBtn = document.getElementById('check');
var output = document.getElementById('output');
var usernames = ['bob', 'sally', 'alice', 'roy', 'kate', 'phil'];
function showResult() {
output.innerHTML = usernames.join(', ');
}
function checkUsername() {
if (usernames.indexOf(username.value) < 0) {
usernames.push(username.value);
username.value = '';
} else {
alert('That username is already taken. Try again.');
}
showResult();
}
goBtn.onclick = checkUsername;
showResult();
<label for="username">Name:</label>
<input id="username" name="username" placeholder="username">
<button id="check">Go</button>
<div id="output"></div>
may be this is what you want
// usernameArray contains all the usernames that can't be used
var usernameArray = ['username1','username2','username3'];
// i'm using .kyup() method to get a dynamic result so whenever the user type a letter or
// something else (just one caracter) we check that value against our usernameArray list
$('#username').keyup(function(){
var value = $(this).val();
if(usernameArray.indexOf(value) >= 0){
alert('sorry, try another username ');
}else{
alert('good, you can use this username it is available');
}
});
Related
I'm sure I'm missing something obvious here but I've had a really good look over this, combing for typos and such but I can't see what the problem is. I want this to be a simple form that requires a username/password combination to validate. The usernames/passwords having to match hasn't been implemented yet because my initial testing can't get over this first hurdle of the form always validating!
I've definitely made a solid go at it and I feel bad I'm getting stuck here, even looking over tons of references and comparing them to my own. I'm not even sure if the event listener itself is the problem or if the problem comes from poor coding in the function. Opening console in browser shows me no errors either. Could anybody point out where my issue is? Thanks.
"use strict";
let loginform = document.forms.login;
loginform.addEventListener("submit", checkLogin);
let users = [];
let pwords = [];
users = ["Administrator", "Manager", "Cleric", "Scribe"];
pwords = ["Password01", "Password", "Admin", "P#ssword"];
//*** NOTE: the password for each username is specific. Use the the alignment of the data in the table above (i.e. the password for the Administrator account is Password01, etc.). ***
function checkLogin() {
var usernameInput = loginform.getElementById("Username").value;
var pwInput = loginform.getElementById("Password").value;
//.includes is what we need for the array checking if statements
//For Loop 1
for (usernameInput in users) {
if (!users.includes(usernameInput)) {
window.event.preventDefault();
alert("Your username is incorrect. Please try again.")
loginform.user.focus();
return false;
} else {
//For Loop 2
for (pwInput in pwords) {
if (!pwords.includes(pwInput)) {
window.event.preventDefault();
alert("Your password is incorrect. Please try again.")
loginform.pword.focus();
return false;
}
}
}
}
}
<h1 id="main">Login to Umbrella Corporation</h1>
<div id="container">
<form name="login" action="success.html" method="POST">
<input type="text" name="user" id="Username">
<br>
<br>
<input type="password" name="pword" id="Password">
<br>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</div>
The form element does not have a getElementById.
Change to one of these
var usernameInput = loginform.user.value;
var pwInput = loginform.pword.value;
var usernameInput = loginform.querySelector("#Username").value;
var pwInput = loginform.querySelector("#Password").value;
var usernameInput = document.getElementById("Username").value;
var pwInput = document.getElementById("Password").value;
You do NOT need to loop and then use includes
if (!users.includes(usernameInput))
is enough
Here is an optimised test
function checkLogin(e) { // event is available here
const usernameInput = loginform.user.value;
const pwInput = loginform.pword.value;
if (!users.includes(usernameInput)) {
e.preventDefault();
alert("Your username is incorrect. Please try again.")
loginform.user.focus();
return false;
} / no need for else after a return
if (!pwords.includes(pwInput)) {
e.preventDefault();
alert("Your password is incorrect. Please try again.")
loginform.pword.focus();
}
}
I think the problem here is that you're trying to loop through your data using the input provided:
var usernameInput = loginform.getElementById("Username").value;
for (usernameInput in users) {...}
This won't work. What you can do is find if the username that the user has provided is present in the array.
var usernameInput = loginform.getElementById("Username").value;
const userIndex = users.indexOf(usernameInput);
If a user is found, it will return a valid index, else it'll return a -1. You can use this to throw an error to the user.
You can do the same with the password:
var pwInput = loginform.getElementById("Password").value;
const pwIndex = pwords.indexOf(pwInput);
At the final check, you can compare the two indices. If they are equal, they are the right combo, else it's an incorrect username/password combo.
if(pwIndex === userIndex && pwIndex !== -1){...} // Success
else {...} // Failure
Finally, this is how your JavaScript should look like:
function checkLogin() {
var usernameInput = loginform.getElementById("Username").value;
var pwInput = loginform.getElementById("Password").value;
//.includes is what we need for the array checking if statements
const userIndex = users.indexOf(usernameInput);
const pwIndex = pwords.indexOf(pwInput);
if(userIndex === -1 || pwIndex === -1) {
alert("Your username/password is incorrect"); // Always better to provide a generic error. You don't want malicious users to know which part they're getting wrong.
}
}
This is my code
html input field
<input type="text" size = "3" name="couponadd" id="couponadd"
oninput="myFunction()" class="field" placeholder="Enter Coupon Code" />
Script Code
<script>
var lastval;
function myFunction() {
getting CouponDC,TicketypDC and CouponPrcDC from database
var CouponDC = $('#dbcoupan').val();
var TicketypDC = $('#dbtckettype').val();
var CouponPrcDC = $('#dbprice').val();
var total_price = $('#total_price').val();
Get getcoupon from input
var getcoupon = $("#couponadd").val(),
txt='Invaild Coupon';
check if user enter same coupon
if(getcoupon == lastval )
{
alert('You Cant Enter Same Code Again');
}
if coupon code match with database coupon
else if (getcoupon == CouponDC ) {
$amount=CouponPrcDC;
total_price = total_price * ((100-$amount) / 100);
minus some ammout from total if match
total_price = Math.round(total_price);
document.getElementById('Voucher_value').value = total_price;
}
if coupo don't match with database coupon
else if(getcoupon != CouponDC && getcoupon.length ==5 )
{
alert('WRONG COUPON CODE');
}
**store last value enter in input**
lastval = getcoupon;
$('#total_price').val(total_price);
}
</script>
You can store it in an array and check if it exists before moving ahead.
Pseudo code below:
var couponArr = [];
var getcoupon = $("#couponadd").val();
if($.inArray(getcoupon, couponArr) !== -1) {
alert('Coupon already used, can\'t use again.');
} else {
couponArr.push(getcoupon);
// your code here..
}
inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1 will be returned.
Add a global tag variable and set default to false,use a if condition wrap the code need to run,then in the run code set it to true.
such as:
// in outer space
var hasCodeRun = false;
// in some function
if (!hasCodeRun) {
// run code here
hasCodeRun = true;
}
I'm having a problem attempting to add data to Firebase. Disregard the vars I don't use as I am trying different things and have commented out stuff I am not using at the moment.
But essentially, what I want to do is save this data to Firebase as follows:
A user enters his name and age in input boxes and then hits submit.
Once he/she hits submit, the function addFB() runs and ideally would create a child called users, and then under that, create a new child with the newly typed in userName (the User's name from the input box), and store his name and age in that child.
However, nothing is going to Firebase from this. Please help. Thanks in advance!
<h2>Add</h2>
<input type=text" id="userName">
<input type="number" id="userAge">
<button id="btUpdateMessage" margin-bottom="20px" onclick="addFB()"> Update</button>
<script>
var lblCurrentMessage = document.getElementById('lblCurrentMessage'),
userName = document.getElementById('userName'),
btUpdateMessage = document.getElementById('btUpdateMessage'),
userAge = document.getElementById('userAge'),
rootRef = new Firebase('https://********.firebaseio.com');
var usersRef = rootRef.child('users');
function addFB() {
usersRef.child(userName).set({
Name: userName,
Age: userAge
});
userName.value = '';
userAge.value = '';
}
*rootRef = new Firebase('https://********.firebaseio.com');*
The above code is not correct. This is the old method.
Just check the below code. This will help you.
function addFB() {
var userName = document.getElementById('userName'),
userAge = document.getElementById('userAge');
firebase.database().ref('users/' + userName).set({
Name: userName,
Age: userAge
});
}
What about this?
var rootRef = Firebase('https://********.firebaseio.com');
var contactsRef = rootRef .child('users');
function addFB() {
contactsRef.child(userName)
.push({
userName: document.getElementById('userName').value,
userAge: document.getElementById('userAge').value
});
Name.value = '';
Age.value = '';
}
I want to print out a series of error messages on my html page based on what the user enters such as password, user name, address etc., which the information failed to validate.
My code looks like this:
function validate(){
var x,y,z;
x = document.getElementById("name").value;
if (x.length<6){
text="user name too short";
} else {
text="validated";
}
document.getElementById("aka").innerHTML = text;
}
Now I can only validate one input. In this case the input with id "name".
I want to validate all the inputs like password also in this function.
How could I implement that in the function?
I tried adding more if statement followed by another document.getElementById("aka").innerHTML = text, but didnt work and the first didn't print out.
Create a variable and put all the error messages there. Once you have finished, put the value of that variable in the innerHTML of the element you want.
function validate(){
var x, errors = "";
x = document.getElementById("name").value;
if (x.length<6){
errors += "user name too short<br />";
}
x = document.getElementById("password").value;
if (x.length<6){
errors += "password too short<br />";
}
document.getElementById("aka").innerHTML = errors;
}
You can either store all messages inside text variable
var text = "";
if (x.length<6){
text+="user name too short";
}
if(y.lenght<6) {
text+= 'pwd too short';
}
document.getElementById("aka").innerHTML = text;
Other option would be using DOM functions as follows:
document.appendChild(document.createTextNode(text));
var text ="";
text += "user name too short";
text += "<br/>pwd too short";
document.getElementById('out1').innerHTML=text;
document.getElementById('out2').appendChild(document.createTextNode('user name too short'));
document.getElementById('out2').appendChild(document.createTextNode('pwd too short'));
<div id="out1"></div>
<div id="out2"></div>
I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}