If the user enters the string 'secret' in the password field, it should display the text in the last else statement. It is only returning the statement in the first else. Can someone explain why?
var pword = document.getElementById('password'); //create event listener on password field's blur event
pword.addEventListener('blur', passwordCheck, false);
var messageField = document.createElement('div');
messageField.setAttribute('id', 'forMessage');
var fieldPassword = document.getElementById('password');
//get form id to create parentNode for message field
var form = document.getElementById('form');
//append form to add message field div
form.appendChild(messageField);
//add message to messageField
var paragraph = document.createElement('p');
function passwordCheck(){ //check to make sure the password is equal to the string "secret"
if (fieldPassword !=='secret'){
var wrongPassword = document.createTextNode('That is not the right password');
paragraph.appendChild(wrongPassword);
messageField.appendChild(paragraph);
}else{
var correctPassword = document.createTextNode('Good... That is the right password');
paragraph.appendChild(correctPassword);
messageField.appendChild(paragraph);
console.log('made it');
}
}
fieldPassword is the input element, not the value, so try:
fieldPassword.value !== 'secret'
Instead of:
fieldPassword !== 'secret'
Look what you did:
var pword = document.getElementById('password');
then again
var fieldPassword = document.getElementById('password');
Why? - pword and fieldPassword are same objects.
Anyway, to the point. The expression fieldPassword !== 'secret' will always be true because fieldPassword is a DOM element, and not a string.
If you had something like <input type="password" id="password">, then you could get the clear password text from the value property of the input element.
What you probably want to do is in the line of if(fieldPassword.value !== 'secret')
Related
Basic form validation
In this question, you’re going to make sure a text box isn’t empty. Complete the following steps:
Create a text input box.
Write a function that turns the text box’s border red if the box is empty.
(It’s empty if the value equals "").
The border should go back to normal if the value is not empty.
When the user releases a key (onkeyup), run the function you just created.
please correct my code where I'm coding wrong?
let form = document.getElementById("form_Text").value;
document.getElementById("form_Text").onfocus = function() {
if (form == "") {
document.getElementById("form_Text").style.backgroundColor = "red";
document.getElementById("showText").innerHTML = "Form is empty";
} else {}
document.getElementById("form_Text").onkeyup = function() {
document.getElementById("form_Text").style.backgroundColor = "white";
document.getElementById("showText").innerHTML =
"Form is not Empty, No red Background";
};
};
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
You are trying to get the input value with let form = document.getElementById("form_Text").value; right after the js is loaded. Therefore it will always be empty. You need to call it inside the event listener.
document.getElementById("form_Text").onfocus = function() {
let form = document.getElementById("form_Text").value;
...
}
But instead of writing two separate event listeners, you can use input event instead of focus and keyup
const formText = document.getElementById("form_Text");
const showText = document.getElementById("showText");
formText.addEventListener('input', function(evt) {
const inputValue = evt.target.value;
if (inputValue == '') {
formText.style.backgroundColor = "red";
showText.innerHTML = "Form is empty";
} else {
formText.style.backgroundColor = "white";
showText.innerHTML = "Form is not Empty, No red Background";
}
})
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
UPDATE
You can find the other way of binding below. Instead of using two separate events (keyup and focus), you can use oninput event listener.
Here's a SO thread comparing keyup and input events: https://stackoverflow.com/a/38502715/1331040
const formText = document.getElementById("form_Text");
const showText = document.getElementById("showText");
formText.oninput = function(evt) {
const inputValue = evt.target.value;
if (inputValue == '') {
formText.style.backgroundColor = "red";
showText.innerHTML = "Form is empty";
} else {
formText.style.backgroundColor = "white";
showText.innerHTML = "Form is not Empty, No red Background";
}
}
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
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 have a requirement to capture into eVar a string of fields that have been changed when user updated their details.
I am using DTM and am thinking how to make it work.
Firstly I wrote this code and saved it as Data Element in the DTM:
var oldMobileNo = document.getElementById('mobileNumber').value;
var oldAnotherNo = document.getElementById('additionalTelephoneNumber').value;
var oldEmail = document.getElementById('emailConfirmed').value;
document.forms['editContactVO'].onsubmit = function(){
var newMobileNo = document.getElementById('mobileNumber').value;
if(oldMobileNo != newMobileNo) {
var MobileNo = "mobile number changed";
}
else {
var MobileNo = "";
}
var newAnotherNo = document.getElementById('additionalTelephoneNumber').value;
if(oldAnotherNo != newAnotherNo) {
var AnotherNo = "additional number changed";
}
else {
var AnotherNo = "";
}
var newEmail = document.getElementById('emailConfirmed').value;
if(oldEmail != newEmail) {
var Email = "email changed";
}
else {
var Email = "";
}
return MobileNo;
return AnotherNo;
return Email;
}
var Final = MobileNo + "," + AnotherNo + "," + Email;
return Final;
Then I tried to reference it with the event based rule set on the form submit button click. The rule definitely worked until I called this Data Element. The rule stopped working.
As far as I understand this code has to be set on the page with form to be able to capture original values and it should be active when the form is updated.
Is it possible to this via DTM? If yes, how to? Or may be somebody did it in the different way?
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');
}
});
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!";
}
}