Change display property onfocus/onblur - javascript

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

Related

Javascript Html Event handling

When I use this code, I am unable to get it to display the data upon clicking the display button. The code is supposed to save the input upon clicking the next button and display the array upon clicking display and clear the array when clicking clear. How do I go about resolving this?
Whenever I click the buttons nothing happens. I want to display the array inside the text area.
<html>
<head>
<script language = "javascript">
var full_name;
var dob;
var gender;
var memberList= new Array();
function saveMember() {
// getElementById may only be used to get one item at a time
// store the .value in the variable
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
// add the values to the array
// (when storing the contents of a variable, use the variable name without quotes)
memberList.push(full_name, dob, gender);
}
function displayMembers() {
var str = " ";
var listLength = memberList.length;
// append all the elements in the array into a single string
for(var i = 0; i < listLength; i+=3) {
str += memberList[i]+", "+memberList[i+1]+", "+memberList[i+2]+"\n";
}
// Replace the contents of the textarea with the value in str
document.getElementById("textBox").value = str;
}
function clearList() {
memberList = [];
}
</script>
<title>INTERNET TECHNOLOGIES CLUB MEMBER LIST </title>
</head>
<body>
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" id = "full_name" value = ""/>
Date of Birth: <input type = "text" id ="dob" value = ""/>
<br>
Gender: <input type = "text" id = "gender" value = ""/>
<br>
<textarea id = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick ="saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()">
</button>
<input type = "button" value = "CLEAR" onclick ="clearList()"></button>
</form>
</body>
</html>
your code is working..remove </button> in your html
I thing you expecting like this: declare the array like var memberList= [];.If you click the clear button Array was empty and textarea also empty.If you need only empty with array.remove document.getElementById("textBox").value=""; in clearlist()
var full_name;
var dob;
var gender;
var full_name;
var memberList= [];
function saveMember() {
// getElementById may only be used to get one item at a time
// store the .value in the variable
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
// add the values to the array
// (when storing the contents of a variable, use the variable name without quotes)
memberList.push(full_name, dob, gender);
}
function displayMembers() {
var str = " ";
var listLength = memberList.length;
// append all the elements in the array into a single string
for(var i = 0; i < listLength; i+=3) {
str += memberList[i]+", "+memberList[i+1]+", "+memberList[i+2]+"\n";
}
document.getElementById("textBox").value = str;
}
function clearList() {
memberList = [];
document.getElementById("textBox").value="";
}
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" id = "full_name" value = ""/>
Date of Birth: <input type = "text" id ="dob" value = ""/>
<br>
Gender: <input type = "text" id = "gender" value = ""/>
<br>
<textarea id = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick ="saveMember()">
<input type = "button" value = "DISPLAY" onclick ="displayMembers()">
<input type = "button" value = "CLEAR" onclick ="clearList()">
</form>
you have written "</button>" as closing tag, which is incorrect syntax for input tag.
<input type = "button" value = "NEXT" onclick ="saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()"></button>
<input type = "button" value = "CLEAR" onclick ="clearList()"></button>
replace this with the following and your code will work fine.
<input type = "button" value = "NEXT" onclick ="saveMember()"/>
<input type = "button" value = "DISPLAY" onclick ="displayMembers()"/>
<input type = "button" value = "CLEAR" onclick ="clearList()"/>
also change these functions for proper functioning
function saveMember() {
full_name = document.getElementById('full_name').value;
dob = document.getElementById('dob').value;
gender = document.getElementById('gender').value;
memberList.push(full_name, dob, gender);
document.getElementById('full_name').value = "";
document.getElementById('dob').value = "";
document.getElementById('gender').value = "";
}
function clearList() {
memberList = [];
document.getElementById("textBox").value = str;
}

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

Trying to add an option to select with append, and nothing happens

My code has two sections: a section to input new items, and a section to interact with them. I'm trying to update the dropdown list every time a new item is added with jQuery, but my current method does nothing. By nothing, I mean that the dropdown list would remain empty. I've tried previous answers to this question, but none worked. (I'm pretty new to Javascript, so me just being a noob is completely possible).
Here's the html:
<!DOCTYPE html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "deletion.css"></link>
<script src = 'chemical.js'></script>
</head>
<body>
<form id = "newChemicalForm">
<p id = newChemicalText> Submit new chemicals here: </p>
<input type = "text" id = "newChemicalInput" onfocus = "this.select()" placeholder = "Enter new chemical here"/>
<button id = "newChemicalButton" onclick = "addChemical()" > Submit </button>
</form>
<form id = "newUsageForm">
<p id= "newUsageText"> Name your chemical and a usage amount. Check if the usage is daily. </p>
<select id = "chemicalDropdown">
</select>
<input type = "text" id = "newUsage" placeholder = "Ex: 250"/>
<input type = "checkbox" id = 'dailyCheckbox'/>
<p id = "dateText"> Enter the end date below: </p>
<input type = "date" id = "dateInput"/>
<button id = "newUsageButton" onclick = "addUsage()"> Submit </button>
</form>
</body>
And the Javascript:
chemicals = [];
function addChemical() {
var chemical = new Chemical();
chemicals.push(chemical);
$('#chemicalDropdown').append('<option value = "' + chemical.name + '"> ' + chemical.name + '</option> \n');
}
function Chemical() {
this.name = $('#newChemicalInput').val();
this.amount = 0;
this.usages = [];
}
There are a couple of things going on. First of all, When you press the submit button it tries to submit the first form. Second: It seems like the onclick event is not binding to the method which should add the item to the dropdownlist.
I've updated a couple of things:
Added $(document).ready(...); as it is best practice.
I've removed the inline onclick and bind the click event via jQuery.
JSFiddle here...
<form id = "newChemicalForm">
<p id = newChemicalText> Submit new chemicals here: </p>
<input type = "text" id = "newChemicalInput" onfocus = "this.select()" placeholder = "Enter new chemical here"/>
<button type="button" id = "newChemicalButton" > Submit </button>
</form>
<form id = "newUsageForm">
<p id= "newUsageText"> Name your chemical and a usage amount. Check if the usage is daily. </p>
<select id = "chemicalDropdown">
</select>
<input type = "text" id = "newUsage" placeholder = "Ex: 250"/>
<input type = "checkbox" id = 'dailyCheckbox'/>
<p id = "dateText"> Enter the end date below: </p>
<input type = "date" id = "dateInput"/>
<button id = "newUsageButton" onclick = "addUsage()"> Submit </button>
</form>
and the JS:
$(document).ready(function(){
var chemicals = [];
$("#newChemicalButton").on("click",function(){
addChemical();
});
function addChemical() {
var chemical = new Chemical();
chemicals.push(chemical);
$('#chemicalDropdown').append("<option value=" + chemical.name + ">" + chemical.name + "</option>");
}
function Chemical() {
this.name = $('#newChemicalInput').val();
this.amount = 0;
this.usages = [];
}
});
Possible the "\n" behind the append code make this not working. Try to remove it.

Handler not working in JavaScript

see the following code :
<html>
<head>
<script type="text/javascript">
function validate()
{
fname = f.fn.value;
if(fname!= "abc")
alert("Incorrect name!")
lname = f.ln.value;
if(lname != "xyz")
alert("Incorrect Name!")
paswd = f.pswd.value;
if(paswd<8)
alert("Too short password!")
for(var i=0; i<f.d.length; i++)
{
if(f.d[i].value.checked)
{
document.write(f.d[i].value);
}
}
for(var i=0; i<f.c.length; i++)
{
if(f.c[i].value.checked)
{
alert(f.c[i].value);
}
}
}
</script>
</head>
<body>
<form name="f" onsubmit="validate()">
First Name: <input type = "text" name = "fn"> <br>
Last Name: <input type = "text" name = "ln"> <br>
Password: <input type = "password" name = "pswd"> <br>
E-mail: <input type = "email" name = "mail"> <br>
Degree : <input type = "radio" name = "d" value = 's'> SE
<input type = "radio" name = "d" value = 'c'>CS
<input type = "radio" name = "d" value = 'E'>IT <br>
University
<select name = "uni">
<option value = 'p'>PU</option>
<option value = 'f'>FAST</option>
</select> <br>
CGPA : <input type = "radio" name = "c" value = '3'> >=3.0
<input type = "radio" name = "c" value = '2'> >=2.5 <br>
Browse <input type = "file" name = "uf"> <br>
<input type = "Submit" value = "Submit">
</form>
</body>
</html>
When i press the submit button,I should get a message of
Incorrect name
or
too short password
if the conditions are true but nothing happens, why?
Why the
validate()
function not running?
The Problem
int i
makes no sense. This would be proper Java syntax, but not in Javascript. I think you mean var i
What else?
You have two form tags.
PS
If you're too lazy to open your web browser's console (or if it doesn't have one), just use the try and catch expressions.
I'm too lazy to fix all these issues. Just give me the fixed code
DEMO
First of all:
Just use form once:
<form> // <--- remove this line
<form name="f" onsubmit="validate()">
Second, you're using a mixture of what seems like JAVA and JavaScript, so instead of for(int i, declare your variable with var. Like so:
for (var i = 0; i < f.d.length; i++) { <--- var instead of int
if (f.d[i].value.checked) {
alert(f.d[i].value);
}
}
That should remove all the errors, you could have also seen these errors yourself when using the correct debugging tools. Here is a list of them:
Chrome DevTools: https://developers.google.com/chrome-developer-tools/docs/console
Firebug: http://getfirebug.com/
For Internet Explorer: http://msdn.microsoft.com/en-us/library/ie/dn255006(v=vs.85).aspx
Couple of error in your code
<html>
<head>
<script type="text/javascript">
function validate()
{
fname = document.f.fn.value;
if(fname!= "abc")
alert("Incorrect name!");
lname = f.ln.value;
if(lname != "xyz");
alert("Incorrect Name!");
paswd = f.pswd.value;
if(paswd<8)
alert("Too short password!")
for(i=0; i<f.d.length; i++)
{
if(f.d[i].value.checked)
{
document.write(f.d[i].value);
}
}
for(i=0; i<f.c.length; i++)
{
if(f.c[i].value.checked)
{
alert(f.c[i].value);
}
}
// return false; // use this you don't want to submit form
// return true; //for advancing the form
}
</script>
</head>
<body>
<form action="" name="f" onsubmit=" return validate()">
First Name: <input type = "text" name = "fn"> <br>
Last Name: <input type = "text" name = "ln"> <br>
Password: <input type = "password" name = "pswd"> <br>
E-mail: <input type = "email" name = "mail"> <br>
Degree : <input type = "radio" name = "d" value = 's'> SE
<input type = "radio" name = "d" value = 'c'>CS
<input type = "radio" name = "d" value = 'E'>IT <br>
University <select name = "uni">
<option value = 'p'>PU</option>
<option value = 'f'>FAST</option>
</select> <br>
CGPA : <input type = "radio" name = "c" value = '3'> >=3.0
<input type = "radio" name = "c" value = '2'> >=2.5 <br>
Browse <input type = "file" name = "uf"> <br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
above code is working
I consider that you are performing validation on this form hence you need to the call the function
return validate();
Now if function return false, the form is not submitted
if function return true, the form is submitted
Do ask for further help , Don't waste my effort's

blur event and javascript/html

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..

Categories