trying to show and hide parts of an html document - javascript

Here is the HTML for my page :
<!DOCTYPE html>
<html>
<body>
<link href = "sites.css" type = "text/css" rel = "stylesheet"/>
<image src = "beach_houses.jpg" id = "sites">
<form id = "details">
Please enter your name: <input type = "text" id = "name"><br/><br/>
Please provide a valid e-mail: <input type = "text" id = "e-mail"><br/><br/>
I am on a tour<input type = "checkbox" id = "status">
<div id = "further"><br/>
Indicate your gender
M<input type = "radio" name = "gender"value = "male" id = "M">
F<input type = "radio" name = "gender" value = "female" id = "F">
</div><br/></br>
<input type = "submit" value = "submit!">
</form>
<br/><br/><div id = "error" ></div>
</body>
<script src = "function.js" type = "text/javascript"></script>
</html>
And here's the javascript :
Images.onclick = function() {
clearInterval(iHandle);
}
function prepare() {
document.getElementById("status").onclick = function() {
if (document.getElementById("status").checked)
document.getElementById("further").style.display = "block";
else
document.getElementById("further").style.display = "none";
document.getElementById("further").style.display = "none";
};
document.getElementById("details").onsubmit = function() {
if(document.getElementById("name").value == "") {
document.getElementById("error").innerHTML = "Please provide a name!";
document.getElementById("error").style.color = "red";
return false;
}
else if (document.getElementById("e-mail").value == "") {
document.getElementById("error").innerHTML = "Please provide a valid e-mail address!";
document.getElementById("error").style.color = "red";
return false;
}
};
}
window.onload = function() {
prepare();
};
The idea is that when the I am on a tour checkbox is checked, the Indicate your gender question pops up. However, the opposite happens; that question seems to be visible by default and becomes invisible when I click on the checkbox. Why is this?
Thanking You in advance
saad

Change <div id = "further"> to <div id = "further" style="display:none">
and
document.getElementById("status").onclick = function() {
if (document.getElementById("status").checked) {
document.getElementById("further").style.display = "block";
}
else {
document.getElementById("further").style.display = "none";
}
};

Related

change the background and color of an input field based on the date using moment.js

I need to change the background and color of an input field based on the date using moment.js I have the some code below, but it finds the date value and then doesn't change the color. I wonder why it doesn't. I'll accept any good answer in javascript or jquery.
var cccr_mems = [
{ "Name": "Ahmed, Jamshed", "cccrEXP": "2018.10.10" },
{ "Name": "Attaya, James J", "cccrEXP": "2019.01.12" },
{ "Name": "Badamo, Anthony", "cccrEXP": "2018.09.12" }]
function getExpireDate(ele) {
var i = null;
for (i = 0; cccr_mems.length > i; i++) {
if (cccr_mems[i].Name == ele.value) {
var exDate = moment(cccr_mems[i].cccrEXP, 'YYYY.MM.DD');
// everything works except for this next "if" statement:
// I would rather reference the input date field by ID such as id = "CCCR_X1"
if (moment().isAfter(exDate)) {
$(ele).closest('.universal').find('.CCCRexpDate').css('color', "#A3005B");
} else {
$(ele).closest('.universal').find('.CCCRexpDate').css('color', "#275052");
}
// down to here.
return cccr_mems[i].cccrEXP;
}
}
return '';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
<input type = "text" onblur="getExpireDate();" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X1" />
<input type = "text" onblur="getExpireDate();" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X2" />
<input type = "text" onblur="getExpireDate();" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X3" />
this might help
first pass reference of element in getExpireDate
<input type = "text" onblur="getExpireDate(this);" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X1" />
<input type = "text" onblur="getExpireDate(this);" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X2" />
<input type = "text" onblur="getExpireDate(this);" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X3" />
then update getExpireDate
function getExpireDate(ele) {
var i = null;
for (i = 0; cccr_mems.length > i; i++) {
if (cccr_mems[i].Name == ele.value) {
var exDate = moment(cccr_mems[i].cccrEXP, 'YYYY.MM.DD');
if (moment().isAfter(exDate)) {
//$(ele).css('color', "#A3005B");
$(ele).css('background', "#A3005B");
} else {
$(ele).css('background', "#275052");
//$(ele).css('color', "#275052");
}
return cccr_mems[i].cccrEXP;
}
}
return '';
}
<input type = "text" onblur="getExpireDate(this);" class="CCCRexpDate" name = "cccr_exp" id = "CCCR_X1" />
and the JavaScript section:
document.getElementById(ele.id).style.backgroundColor="#275052"

Javascript to check if fields are entered for login

I'm trying to create a login page. I need to validate username and password but my js does not seem to work. I made it simpler now just for the sake to make it work. This is my html:
<script type="text/javascript" src = "js/checklogin.js"></script>
<h3>Already have an account?</h3>
<span id = "feedback"></span>
<form id = "login" action = "login.html" method = "post">
<label for = "name">User name:</label><br>
<input type = "text" name = "username " id = "username"><br>
<label for = "password">Password:</label><br>
<input type = "password" name = "password" id = "password"><br>
<input type="submit" value="Login">
</form>
And this is my js:
var elUsername = document.getElementById('username');
var elPassword = document.getElementById('password')
var elMsg = document.getElementById('feedback');
function checkFilled(length) {
if (length == "") {
elMsg.innerHTML = 'Please fill out this field';
} else {
document.getElementById("login").submit();
}
}
elUsername.addEventListener('blur', checkFilled(elUsername.value),false);
elPassword.addEventListener('blur', checkFilled(elPassword.value),false);
I still cannot make it to work. Also, how can i make it to appear as a pop up right on the textbox? Something that looks like this:
Error image
There's several issues with the code you had, so here's a complete example of the way I would do it (use the same HTML you already have). This works for me as tested in JSFiddle and below in the snippet.
var elUsername = document.getElementById('username');
var elPassword = document.getElementById('password')
var elMsg = document.getElementById('feedback');
var elForm = document.getElementById('login');
function checkFilled() {
if (elUsername.value == "" || elPassword.value == "") {
elMsg.innerHTML = 'Please fill out this field';
event.preventDefault();
} else {
elMsg.innerHTML = '';
}
}
if (elForm.addEventListener) {
elForm.addEventListener('submit', function() {
checkFilled();
}, false);
} else {
elForm.attachEvent('onsubmit', function() {
checkFilled();
});
}
if (elUsername.addEventListener) {
elUsername.addEventListener('blur', function() {
checkFilled();
}, false);
} else {
elUsername.attachEvent('onblur', function() {
checkFilled();
});
}
if (elPassword.addEventListener) {
elPassword.addEventListener('blur', function() {
checkFilled();
}, false);
} else {
elPassword.attachEvent('onblur', function() {
checkFilled();
});
}
<!--<script type="text/javascript" src = "js/checklogin.js"></script>-->
<h3>Already have an account?</h3>
<span id = "feedback"></span>
<form id = "login" action = "login.html" method = "post">
<label for = "name">User name:</label><br>
<input type = "text" name = "username " id = "username"><br>
<label for = "password">Password:</label><br>
<input type = "password" name = "password" id = "password"><br>
<input type="submit" value="Login">
</form>

Display Form Results in Textarea with JavaScript

I'm new to programming. I've made a form that displays results in a HTML textarea with javascript. I'm trying to make the textarea also display a link to the wikipedia article about the item selected using an if/else statement:
function setFlower(type) {
flowerName = type;
}
//method for displaying the method in the textarea
function displayMessage() {
var fullName = document.flowerOrderForm.fullName.value;
// if/else statements for more information
if (flowerName == document.flowerOrderForm.flowerTypes.roses) {
var moreInfo = "https://en.wikipedia.org/wiki/Rose";
}
else if (flowerName == document.flowerOrderForm.flowerTypes.carnations) {
var moreInfo = "https://en.wikipedia.org/wiki/Dianthus_caryophyllus";
}
else if (flowerName == document.flowerOrderForm.flowerTypes.daisies) {
var moreInfo = "https://en.wikipedia.org/wiki/Asteraceae";
}
document.flowerOrderForm.info.value =
fullName + ", " + "thank you for your inquiry about " + flowerName + "." + NL
+ "Here is a link for more information: " + moreInfo;
}
And the HTML form:
<form name = "flowerOrderForm">
<fieldset name = "form">
<fieldset name = "inputControls">
<p class = "name">
<!--Name textbox and label-->
<label for = "fullName">Full Name</label><br />
<input class = "fullName" type = "text" name = "fullName" value = "" id = "fullName" size = "35" />
</p>
<p class = "flowers">
<!--flower type radio buttons-->
<span>
<input type = "radio" name = "flowerTypes" value = "roses" id = "roses" onclick = "setFlower(this.value)" />
<label for= "roses">Roses</label>
</span>
<span>
<input type = "radio" name = "flowerTypes" value = "carnations" id = "carnation" onclick = "setFlower(this.value)" />
<label for = "carnation">Carnations</label>
</span>
<span>
<input type = "radio" name = "flowerTypes" value = "daisies" id = "daisy" onclick = "setFlower(this.value)" />
<label for = "daisy">Daisies</label>
</span>
</p><!--end flowers-->
</fieldset><!--end inputControls-->
<fieldset name = "submit">
<!--request info submit button-->
<input class = "requestInfo" type = "button" name = "flowerOrder" value = "Request Information" onclick = "displayMessage()" />
</fieldset><!--end submit-->
<fieldset name = "infoBox">
<!--textarea for displaying submitted information-->
<textarea name = "info" readonly = "true" value = "" rows = "7" cols = "50"></textarea>
</fieldset><!--end infoBox-->
</fieldset><!--end form-->
</form>
Right now, moreInfo is undefined in the text area. How can I fix this?
Dont use document.write all it does it print it out to the screen instead store it as link
function setFlower(type) {
flowerName = type;
}
//method for displaying the method in the textarea
function displayMessage() {
var fullName = document.flowerOrderForm.fullName.value;
var moreInfo;
// if/else statements for more information
if (flowerName == document.flowerOrderForm.flowerTypes.roses) {
moreInfo = "https://en.wikipedia.org/wiki/Rose";
}
else if (flowerName == document.flowerOrderForm.flowerTypes.carnations) {
moreInfo = "https://en.wikipedia.org/wiki/Dianthus_caryophyllus";
}
else if (flowerName == document.flowerOrderForm.flowerTypes.daisies) {
moreInfo = "https://en.wikipedia.org/wiki/Asteraceae";
}
document.flowerOrderForm.info.value =
fullName + ", " + "thank you for your inquiry about " + flowerName + "." + NL
+ "Here is a link for more information: " + moreInfo;
// moreInfo would be a link now as a string and so will be displayed in textarea
}

result output disappears too quickly

the correct or wrong answer outputs and quickly disappears. How do I get the answer to remain on the screen. I want to keep the html and js files separate. What I want to do later is add other phrases to the program.
INDEX.HTML
<head> </head>
<body>
<form name="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput">
<button id="myBtn">Click here</button>
<div id ="feedback"></div>
</form>
<script src = "phraseScrambler.js"></script>
</body>
</html>
PHRASESCRAMBLER.JS
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myBtn").onclick = checkAnswer;}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent= "correct";}
else {
elMsg.textContent= "wrong answer";}}
function shuffle(newWords) {
var counter = newWords.length, temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;}
return newWords;}
First of all don't bind click event if you want to handle form submission, forms have dedicated event called onsubmit. When form is submitted default browser behavior is to navigate to form action (in your case reload the page). You need to prevent this by returning false from the onsubmit handler.
Corrected HTML will be (I gave an id to the form):
<form name="myForm" id="myForm"> ... </form>
And then event handling will look like (note return false; in checkAnswer function):
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myForm").onsubmit = checkAnswer;
}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent = "correct";
} else {
elMsg.textContent = "wrong answer";
}
return false;
}
function shuffle(newWords) {
var counter = newWords.length,
temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;
}
return newWords;
}
<form name="myForm" id="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput" />
<button>Click here</button>
<div id ="feedback"></div>
</form>

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

Categories