blur event and javascript/html - javascript

I have to ask for a user's name and id number. Using event handlers such for blur or submit events and check that the user text box isn't empty and the id is a number and I have to put up an alert box if false.
Here is my html:.
<form id = "form" action = "">
<p>
<label class = "classname" for = "name">Username:</label>
<input type = "text" id = "name" placeholder = "enter your Username">
</p>
<p>
<label class = "classname" for = "idnum">ID Number:</label>
<input type = "text" id ="idnumber" placeholder = "enter id number">
</p>
</form>
and here is my Javascript code:
var helpArray = ["your doing it wrong", "your wrong"]
var helpText;
function init(){
helpText = document.getElementById("helpText");
registerListeners(document.getElementById("name"),0);
registerListeners(document.getElementById("idnumber"),0);
}
function registerListeners(object, messageNumber){
object.addEventListener( "blur",function(){
helpText.innerHTML = helpArray [0];
}, false);
object.addEventListener( "focus",function(){
helpText.innerHTML = helpArray [messageNumber];
}, false);
}
window.addEventListener("load",init,false);
as you can see I have been just trying to go by my textbook, haven't made much progress.

Instead of calling functions too many times you can use simple code like the one below.Calling functions in javascript many times may result in performance costs
window.onload = init;
function init(){
helpText = document.getElementById("helpText");
document.getElementById("name").onblur = function() {
helpText.innerHTML = helpArray [0];}, false);
}
document.getElementById("idnumber").onblur = function() {
helpText.innerHTML = helpArray [0];}, false);
}
}
you can assign functions to any events like above example, you may also use onfocus,onkeyUp..etc..

Related

Using the required attribute on a password input

I'm trying to set a password input as required in JavaScript.
I have learnt from this post how to do it but it doesn't seem to work with my password input.
<div class = "login">
<input type = "password" class = "enterPassword">
<button class = "submit">Submit</button>
</div>
var p = document.querySelector(".enterPassword");
p.required = true;
p.style.backgroundColor = "gray";
var s = document.querySelector(".submit");
s.addEventListener("click", clickHandler.bind(p));
function clickHandler() {
console.log("Password: " + this.value);
}
jsfiddle
Although I do,
var p = document.querySelector(".enterPassword");
p.required = true;
as you can see, there is no required popup when a user fails to enter a password. Does anyone know why not?
Wrap the elements in a form
<form>
<input type = "password" class = "enterPassword">
<button class = "submit">Submit</button>
</form>
You can also check it without using form
document.querySelector(".enterPassword").validity.valid
this will return a Boolean value , but you wont see the error pop up
JSFIDDLE

Change display property onfocus/onblur

I've looked up a few other questions on the site, but am still at a loss. I wanted to use Javascript (no JQuery) to take the form below:
<!doctype html>
<html>
<head>
<meta charset = "UTF-8"/>
<title>Account Sign-Up</title>
</head>
<body>
<h1>Profile Sign-Up</h1>
<fieldset>
<p>
<p><label for = "first_name">First Name: </label>
<input type = "text" id = "first_name" onfocus = "javascript:showText(1)"/>
<div id = "div1" style = "display:none">Enter your first name</div>
<p><label for = "last_name">Last Name: </label>
<input type = "text" id = "last_name" onfocus = "showText(2)"/>
<div id = "div2" style = "display:none">Enter your last name</div>
<p><label for = "email">E-Mail: </label>
<input type = "text" id = "email" onfocus = "showText(3)"/>
<div id = "div3" style = "display:none">Enter E-Mail</div>
<p><label for = "username">Username: </label>
<input type = "text" id = "username" onfocus = "showText(4)"/>
<div id = "div4" style = "display:none">Enter your desired screen name</div>
<p><label for = "password">Password: </label>
<input type = "password" id = "password" onfocus = "showText(5)"/>
<div id = "div5" style = "display:none">Enter the password you will use to log into your account in the future</div>
<p><label for = "retype_password">Retype your password again: </label>
<input type = "password" id = "retype_password" onfocus = "showText(6)"/>
<div id = "div6" style = "display:none">Type your password again</div>
<p><button name = "submit" type = "button" id = "submit">Submit</button>
</p>
</fieldset>
<script src = "Q10.js"></script>
</body>
</html>
and apply the following script to display some hidden text whenever the text boxes gain focus. I don't wish to go beyond the scope of what is described. So no, I can't use pop-up tooltips or text in a single div element in a footer, etc. I'm also unconcerned with data injections or the vulnerability/security of the code, as I am not using it for anything practical.
var enableBtn = function () {
document.getElementById("submit").disabled = false;
};
//function enables submit button
var disableBtn = function () {
document.getElementById("submit").disabled = true;
};
//disables submit button
var checkInput = function () {
if (document.getElementById("password").value.length > 0 && document.getElementById("username").value.length > 0 && document.getElementById("password").value === document.getElementById("retype_password").value) {
enableBtn();
}
else {
disableBtn();
}
};
var showText = function (numb) {
document.getElementById("div" + numb).style = "display:inline";
};
var hideText = function(numb) {
document.getElementById("div" + numb).style = "display:none";
};
document.onfocus = checkInput
//if password and username have an input- and retype password is the same as password, button is usable. If not, it's disabled.
document.getElementById("retype_password").oninput = checkInput;
document.getElementById("password").oninput = checkInput
//document.getElementById("password").onclick = function() {alert(document.getElementById("password").value.length)};
//
I'm currently running into a hiccup because I can't get the events to run scripts on focus, and don't know where else to turn. Please help ><
I'm not sure whether this is the way you want it, check the snippet. If not i will close down this answer. what i did is to add/change some code in showText(). and i think it would be better to show those divs you used on hiding texts to span(or <p>)tag as well. i added css for hiding texts class named description. you can remove other codes that you made which is not useful.
var enableBtn = function () {
document.getElementById("submit").disabled = false;
};
//function enables submit button
var disableBtn = function () {
document.getElementById("submit").disabled = true;
};
//disables submit button
var checkInput = function () {
if (document.getElementById("password").value.length > 0 && document.getElementById("username").value.length > 0 && document.getElementById("password").value === document.getElementById("retype_password").value) {
enableBtn();
}
else {
disableBtn();
}
};
var showText = function(numb) {
var desc = document.getElementsByClassName("description");
for (var i = 0; i < desc.length; i++) {
desc[i].style.display ="none";
}
document.getElementById("div" + numb).style.display = "inline";
};
var hideText = function(numb) {
document.getElementById("div" + numb).style = "display:none";
};
document.onfocus = checkInput
//if password and username have an input- and retype password is the same as password, button is usable. If not, it's disabled.
document.getElementById("retype_password").oninput = checkInput;
document.getElementById("password").oninput = checkInput
//document.getElementById("password").onclick = function() {alert(document.getElementById("password").value.length)};
.description:before {
content: '*';
}
.description {
display: none;
color: red;
}
<h1>Profile Sign-Up</h1>
<fieldset>
<p>
<p><label for = "first_name">First Name: </label>
<input type = "text" id = "first_name" onfocus = "javascript:showText(1)"/>
<span id="div1" class="description">Enter your first name</span>
<p><label for = "last_name">Last Name: </label>
<input type = "text" id = "last_name" onfocus = "showText(2)"/>
<span id="div2" class="description">Enter your last name</span>
<p><label for = "email">E-Mail: </label>
<input type = "text" id = "email" onfocus = "showText(3)"/>
<span id="div3" class="description">Enter E-Mail</span>
<p><label for = "username">Username: </label>
<input type = "text" id = "username" onfocus = "showText(4)"/>
<span id="div4" class="description">Enter your desired screen name</span>
<p><label for = "password">Password: </label>
<input type = "password" id = "password" onfocus = "showText(5)"/>
<span id="div5" class="description">Enter the password you will use to log into your account in the future</span>
<p><label for = "retype_password">Retype your password again: </label>
<input type = "password" id = "retype_password" onfocus = "showText(6)"/>
<span id="div6" class="description">Type your password again</span>
<p><button name = "submit" type = "button" id = "submit">Submit</button>
</p>
</fieldset>
<!-- <script src = "Q10.js"></script> -->
It should work fine but there could be possible Problems:
1.If you are running this on JSFiddle then you can try. window.showText. Working fiddle: https://jsfiddle.net/24sck8rs/5/
window.showText = function (numb) {
document.getElementById("div" + numb).style = "display:inline";
};
2.Possible cause of hoisting. I have declared function variable at the top and removed var. Working fiddle: https://jsfiddle.net/24sck8rs/6/
3.Declare your script in head before function call

Why doesn't my reset() function remove my red error lines?

function validate() {
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if (checkfname() == true) {
alert("Entry submitted.");
} else {
return false;
}
}
function checkfname() {
var fname = document.getElementById("fname").value;
if (fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
} else if (!isNaN(fname)) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
} else {
return true;
}
}
function addRow() {
if (validate() == true) {
}
}
<form>
First Name:
<input type="text" id="fname" name="fname" />
<p id="errorfname" class="red"></p>
<input id="submit" type="submit" value="Submit Entry" onclick="return addRow()" />
<input id="clear" type="button" value="Reset" onclick="reset()" />
</form>
<form>
<fieldset>
<label for = "firstnameinput">
First Name: <input type = "text" id = "fname" name = "fname" placeholder = "John"/>
<p id = "errorfname" class = "red"></p>
</label>
</fieldset>
<fieldset>
<label id = "submitbutton">
<input id = "submit" type = "submit" value = "Submit Entry" onclick = "return addRow();upperCase();"/>
</label>
<label id = "resetbutton">
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
</label>
</fieldset>
</form>
This is my simplified HTML file. It basically has an input and a paragraph below it to display an error message later on. For now it is set as "" in javascript. The HTML also has a submit button and a reset button. The purpose of the reset button is to clear all previously entered fields or any error message that has appeared.
function validate(){
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if(checkfname() == true){
alert("Entry submitted.");
}
else{
return false;
}
function checkfname(){
var fname = document.getElementById("fname").value;
if(fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
}
else if(!isNaN(fname)){
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
}
else{
return true;
}
}
function addRow(){
if(validate() == true){
event.preventDefault();
var fname = document.getElementById("fname").value;
firstNameArray.push(fname)
var row = document.getElementById('table').insertRow(-1);
var colNum = row.insertCell(0);
var colName = row.insertCell(1);
i++;
colNum.innerHTML = i;
colName.innerHTML = fname + " " + lname;
else{
return false;
}
reset();
}
Lastly, my reset() function below.
function reset(){
document.getElementById("errorfname").innerHTML = "";
document.getElementById("fname").value = "";
}
The problem is, for example, in the input box for fname, I enter John. When I press the reset button on my HTML which calls the reset() function, John in the box disappears so I got that going for me which is nice. However, lets say I purposely left the box blank to receive an error message, a red sentence below the box appears saying "Invalid first name. Cannot be empty." When I press the reset button to call onto the reset() function, this red error message does not disappear however, any current value inside the box disappears. This makes by reset() function work 50% only. I clearly stated for both to disappear in my reset() function.
TL;DR
I have a reset button in my HTML which calls a reset() function in my javascript. I have a name input box in my HTML and what the reset() function is supposed to do is to remove any current name which is inside the box as well as remove any error message that appears below. My reset() function is able to clear away any name inside the box currently but is unable to clear away the error message.
I created a fiddle to test your problem. I noticed the same thing. I changed the method reset() to resetTest() and it worked fine.
working fiddle
The reason changing the name worked is that onxyz= attribute event handlers are run (effectively) within a couple of with statements, one of which is with (theEnclosingFormElement). Form elements have a built-in reset method that clears all of their inputs to their initial values. So in this:
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
The reset being called isn't your reset, it's the form's reset, which doesn't (of course) do anything with errorfname. Changing the name removes the conflict.

why are names not being added to the list?

I found this fiddle and I am trying to get it to work...I can not figure out why the names are not being added to the list, for some reason Add button is acting like a submit button and I can not tell why...It should add all the numbers to a list so when I click submit, then it should send the numbers in an array..
JavaScript:
function bindName() {
var inputNames = document.getElementById("names").getElementsByTagName("inputNames");
for (i = 0; i < inputNames.length; i++) {
inputNames[i].onkeydown = function() {
if (this.value == "") {
setTimeout(deletename(this), 1000);
}
}
}
}
document.getElementById("addName").onclick = function() {
var num1 = document.getElementById("name");
var myRegEx = /^[0-9]{10}$/;
var myRegEx = /^[0-9]{10}$/;
var itemsToTest = num1.value;
if (myRegEx.test(itemsToTest)) {
var form1 = document.getElementById("names");
var nameOfnames = form1.getElementsByTagName("inputNames").length;
var newGuy1 = document.createElement("inputNames");
newGuy1.setAttribute("id", nameOfnames);
newGuy1.setAttribute("type", "text");
newGuy1.setAttribute("value", num1.value);
form1.appendChild(newGuy1);
num1.value = "";
bindName();
}
else {
alert('error');
}
};
HTML:
<h1>Enter Name</h1>
<div id="mainName">
<h2>name</h2>
<label for="name">Add Names: </label>
<input id="name" type="text">
<button id="addName">Add</button>
<form>
<div id="names">
</div>
<input METHOD="POST" action="text.php" type="submit" value="Submit">
</form>
</div>
I've seen
document.createElement("inputNames");
Shouldn't be
document.createElement("input");
?
Because this /^[0-9]{10}$/; will accept only 10 numbers and only that, try entering 1234567890 and you will see no error.
I'm not sure why your "name" field is restricted to 10 digit numbers, but I've got the thing to work.
http://jsfiddle.net/y8Uju/4/
I think the problem was that you were trying to create an element with the tag name inputNames, but that's not a valid tag. Instead I changed it to create inputs, and set the class to inputNames.

how to write onblur and onfocus event in javascript?

Question:
<body onload="setBlurFocus()">
<form method="POST" action="#">
<input id="id_username" type="text" name="username" maxlength="100" />
<input type="text" name="email" id="id_email" />
<input type="password" name="password" id="id_password" />
</form>
</body>
I wrote :
function setBlurFocus () {
var user_input = document.getElementById('id_username');
var email = document.getElementById('id_email');
var password = document.getElementById('id_password');
user_input.onblur = userSetBlur();
email.onblur = emailSetBlur();
password.onblur = passSetBlur();
user_input.onfocus = function() {
document.getElementById('id_username').value = ''
}
email.onfocus = function() {
document.getElementById('id_email').value = ''
}
password.onfocus = function() {
document.getElementById('id_password').value = ''
}
}
function userSetBlur() {
document.getElementById('id_username').value = 'Username'
}
function emailSetBlur() {
document.getElementById('id_email').value = 'Email'
}
function passSetBlur() {
document.getElementById('id_password').value = 'Password'
}
Question?
How to generalize or optimized this code?
You can always attach the methods in JavaScript:
function setBlurFocus() {
var user_input = document.getElementById('id_username');
user_input.onblur = someFunction;
// or with an anonymous function:
user_input.onfocus = function() {
// do something
}
}
Read more about traditional event handling and events in general.
Further explanation:
You attached the function setBlurFocus to the load event of the document. This is correct if you have to access DOM elements with JavaScript. The load event is fired when all the elements are created.
If you attach the setBlurFocus() to the blur event of the input field, then the function is only executed when the text box looses focus.
From your question I concluded you don't want set the event handlers in the HTML, but you want to set them form inside the setBlurFocus function.
Regarding your update:
This is wrong:
user_input.onblur = userSetBlur();
This assigns the return value of the function to onblur. You want to assign the function itself, so you have to write:
user_input.onblur = userSetBlur;
The () calls the function. You don't want that (in most cases, there are exceptions, see below).
Furthermore, you don't have to use named functions for onblur and anonymous functions for onfocus. It was just an example, to show you the different possibilities you have. E.g. if you assign an event handler to only one element, then there is no need to define it as extra function. But you have to do this if you want to reuse event handlers.
Here is an improved version:
function setBlurFocus () {
var values = ["Username", "Email", "Password"];
var elements = [
document.getElementById('id_username'),
document.getElementById('id_email'),
document.getElementById('id_password')
];
for(var i = elements.length; i--; ) {
elements[i].onblur = setValue(values[i]);
elements[i].onfocus = emptyValue;
}
}
function setValue(defaultValue) {
return function(){this.value = defaultValue;};
}
function emptyValue() {
this.value = '';
}
this inside the event handlers refers to the element the handler is bound to.
Note: Here setValue returns a function, that is why we call setValue in this case (and not just assign it).
Important note: This will also reset the values to Username etc, if the user entered some data. You have to make sure, that you only reset it if the user has not entered data. Something like:
function setValue(defaultValue) {
return function(){
if(this.value !== "") {
this.value = defaultValue;
}
};
}
and you'd have to define emptyValue similar:
function emptyValue(defaultValue) {
return function(){
if(this.value === defaultValue) {
this.value = "";
}
};
}
Now that I know what you actually want to do, have also a look at HTML5's placeholder attribute.
Well you've tagged it with jquery so this is how to do it in jquery:
function setBlurFocus () {
//do stuff here
}
$('#id_username').blur(setBlurFocus);
or
$('#id_username').blur(function(){
//do stuff here
});
Regarding your update
I using jquery as you tab jquery, the code was bellow , you can check a live sample with this link :
http://jsfiddle.net/e3test/zcGgz/
html code :
<form method="POST" action="#">
<input id="id_username" type="text" name="username" maxlength="100" />
<input type="text" name="email" id="id_email" />
<input type="password" name="password" id="id_password" />
</form>
javascript code :
$(function(){
var selector = {
username: $('#id_username'),
email: $('#id_email'),
password: $('#id_password')
};
for (var x in selector) {
selector[x].focus(function(){
$(this).val('');
}).blur(function(){
$(this).val($(this).attr('name'));
});
}
});
Hope it help.

Categories