how to change display none to block when form submits - javascript

I am learning JSP, javascript and a little jquery in my own time so please don't mind the probably horrible code or logic but I am making a form and when I submit the form I want it to display 3 labels showing the inputs, as seen in the code below I have it working so far as submitting but I can't seem to figure out how to change the CSS display from none to block. It's probably staring at me in the face but I can't figure it out.
JSP
<html>
<body>
<link type="text/css" rel="stylesheet" href="<%=request.getContextPath()%>/dylan/css/styles.css" />
<form action="form.jsp" id="test" name="test" method="POST">
<label>Please enter your name:</label>
<input name="Name" id="Name">
<br>
<br>
<label>Please enter your number:</label>
<input name="Num" id="Num">
<br>
<br>
<label>Please select your location:</label>
<select name="Location" id="Location">
<option value=""></option>
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="Ireland">Ireland</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
</select>
<br>
<br>
<button type="button" id="btnsubmit" name="btnsubmit" onclick="myFunction()">Submit</button>
<br>
<p><label id="lblName" style="display:none;"><% out.println(request.getParameter("Name")); %></label></p>
<p><label id="lblNumber" style="display:none;"><% out.println(request.getParameter("Num")); %></label></p>
<p><label id="lblLocation" style="display:none;"><% out.println(request.getParameter("Location")); %></label></p>
<script type="text/javascript" src="<%=request.getContextPath()%>/dylan/js/form.js"></script>
</form>
</body>
</html>
In the label I am setting the all 3 of the styles to none, I have no idea how to change that to block when submitting the form.
css
body {
background-color:#066;
color:#fff;
}
form {
width:400px;
height:240px;
Background-color:#000;
margin-left:auto;
margin-right:auto;
margin-top:170px;
Padding:10px;
border-style:solid;
border-width:5px;
border-radius:25px;
text-align:center;
}
javascript
function myFunction() {
var mainname, mainnum, mainloc;
mainname = document.getElementById("Name").value;
mainnum = document.getElementById("Num").value;
mainloc = document.getElementById("Location").options[document.getElementById("Location").selectedIndex].value;
if (mainname == "") {
alert("Please enter your name");
return false;
}
if (mainnum == "") {
alert("Please enter your Number");
return false;
}
if (mainloc == '') {
alert("Please select a country from the list");
return false;
}
document.getElementById("test").submit();
}

You can set the display to block as below.
document.getElementById('lblName').style.display = 'block';
document.getElementById('lblNumber').style.display = 'block';
document.getElementById('lblLocation').style.display = 'block';

If you have many labels you could use:
var labels = document.getElementsByTagName('label');
for(var i=0; i<labels.length; i++){
labels[i].style.display = 'block';
}

Related

How To Fill-Up a particular field of HTML form Based On dropdown selection made

Any way of making this code work with a select dropdown instead of a button? I am trying to use this to fill in a address from a dropdown and allow the user to modify as needs are needed.
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var TestVar1 = form.input[0].checked;
var TestVar2 = form.input[1].checked;
if (TestVar1 == true) {
form.textbox.value = "Full Home Automation Package";
} else if (TestVar2 == true){
form.textbox.value = "Some Other Package";
} else if (TestVar1 == false && TestVar2 == false) {
form.textbox.value = "";
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="POST">Choose a Service: <BR>
<INPUT TYPE="radio" NAME="input" VALUE="red" onChange="testResults(this.form)">Service 1<P>
<INPUT TYPE="radio" NAME="input" VALUE="blue" onChange="testResults(this.form)">Service 2<P>
<P>Service Package Selected:</P> <INPUT TYPE="text" ID="textbox" NAME="selected" VALUE=""></div><p>
</FORM>
</BODY>
thanks for any help
You can use onchange on select and then if the value matches change the text of the input.
<!DOCTYPE html>
<html>
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults(value) {
let textbox = document.getElementById("textbox");
if (value === '') {
textbox.value === '';
} else if (value === 'service1') {
textbox.value = 'Full Home Automation Package';
} else if (value === 'service2') {
textbox.value = "Some Other Package";
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="POST">Choose a Service: <BR>
<select onchange="testResults(value)" name="service">
<option disabled selected>Choose one</option>
<option value="service1">service1</option>
<option value="service2">service2</option>
</select>
<P>Service Package Selected:</P> <INPUT TYPE="text" ID="textbox" NAME="selected" VALUE=""></div>
<p>
</FORM>
</BODY>
</html>

Showing Div Not Working On Select Using Javascript

I am trying to show the FILE DIV if the user selects the doctor value in the select statement. I know the if statement works because I also print the value in the console which works perfectly fine. I toggle my divs in the same exact manner in my other webpages so I'm not understanding what's going on with this one in particular.
function viewFile(){
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if(type === 'doctor') {
file.style.display = "block";
console.log(type);
}
}
.hidden{
display : none;
}
<div>
<select id="accountType" name="type" class="form-control" onchange="viewFile()">
<option required>Account Type</option>
<option value="doctor" name="doctor" id="doctor">Doctor</option>
<option value="regular" name="regular" id="reg">Regular Account</option>
</select>
</div>
<div class="hidden file" id="doclicense">
<input type="file" name="license" />
<input type="submit"/>
</div>
****************************************EDIT-WORKAROUND**********************
Since my code refused to work, I added a line of code with 'head' being the title and not a real value. Thanks to everyone who contributed. I took out the hidden class altogether but when I add it, it still doesn't work correctly.
function viewDocFile() {
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if (type === 'regular' || type === 'head') {
file.style.display = "none";
console.log(type);
} else {
file.style.display = "block";
console.log(type);
}
}
***************************FINAL-EDIT************************
Kept the original code, but added the CSS inline.
<div class="form-group col-md-6" id="doclicense" style="display:none;">
Works perfectly now.
Here is an example of how this code should be written (even if there are still horrors)
// declare them here and not in a function where they will be redone each time the function is called
const
file_IHM = document.querySelector('#doclicense')
,
type_IHM = document.querySelector('#accountType') // and not with .value ...!
;
type_IHM.onchange = function()
{
file_IHM.style.display = (this.value==='doctor')?"block":"none";
console.log('type_IHM.value', this.value );
}
#doclicense { display : none; }
<div>
<select id="accountType" name="type" class="form-control" > <!-- let the js in the js part -->
<option required>Account Type</option>
<option value="doctor" id="doctor" >Doctor</option>
<option value="regular" id="regular" >Regular Account</option>
</select>
</div>
<div class="file-class" id="doclicense"> <!-- do not use class="hidden... -->
<input type="file" name="license" />
<input type="submit" /> <!-- there is no form anywhere... why don't you use <button> ?? -->
</div>
If that what your code really looks like, did you add your js in a <script></script> tag?
Or do you want to toggle the hide and show of the div?
if so this answer may help
<select id="accountType" name="type" class="form-control" onchange="viewFile()"><option required>Account Type</option>
<option value="doctor" name="doctor" id="doctor">Doctor</option>
<option value="regular" name="regular" id="reg">Regular Account</option>
</select>
</div>
<div class="hidden file" id="doclicense">
<input type="file" name="license" />
<input type="submit"/>
</div>
<script>
function viewFile(){
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if(type === 'doctor') {
file.style.display = "block";
console.log(type);
}else{
file.style.display = "none";
console.log(type);
}
}
</script>

Form : 2 Separate Paths

I am working on a simple form for work. I found some code online and have been working with it. It starts out asking a simple question. If the student has an ID? It is a toggle of either "YES" or "NO". If "Yes" is selected then it will pull student info from a database and display. If "NO" then separate boxes will pop up asking for the students ID, last name, first name, DOB, etc. Right now I am focusing on the path selection to work. I haven't had any luck.
function admSelectCheck(nameSelect) {
if (nameSelect) {
admOptionValue = document.getElementById("admOption").value;
if (admOptionValue == nameSelect.value) {
document.getElementById("admDivCheck").style.display = "block";
} else {
document.getElementById("admDivCheck").style.display = "none";
}
} else {
document.getElementById("admDivCheck").style.display = "none";
}
}
Student ID
<select id="getFname" onchange="admSelectCheck(this);">
<option value="6"></option>
<option value="1">Yes</option>
<option id="admOption" value="0">No</option>
</select>
<div id="admDivCheck" style="display:none;">
<br><br>
<form action="/action_page.php" method="post">
Please enter ID# <input type="number" name="ID"><br> Last Name <input type="text" name="last"><br> First Name <input type="text" name="first"><br>
<button type="submit">Submit</button>
</div>
How about this? .
function admSelectCheck(nameSelect) {
var value = nameSelect.value;
if (value == "1") {
document.getElementById("id-form").style.display = "block";
document.getElementById("second-div").style.display = "none";
} else if (value == "0"){
document.getElementById("id-form").style.display = "none";
document.getElementById("second-div").style.display = "block";
}
else{
document.getElementById("id-form").style.display = "none";
document.getElementById("second-div").style.display = "none";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src = "test.js"></script>
</head>
<body>
Student ID
<select id="getFname" onchange="admSelectCheck(this);">
<option value="6"></option>
<option value="1">Yes</option>
<option id="admOption" value="0">No</option>
</select>
<form id = "id-form" action="/action_page.php" method="post" style = "display: none">
Please enter ID# <input type="number" name="ID"><br>
Last Name <input type="text" name="last"><br>
First Name <input type="text" name="first">
<br>
<button type="submit">Submit</button>
</form>
<div id = "second-div" style = "display: none">
<br>
<img src = "https://i.ytimg.com/vi/QuTLRz8Nli0/hqdefault.jpg"/>
</div>
</body>
</html>

Form Validation and Alert issues in JavaScript

The following is a complete copy of the project I'm working on. I'm having problems with the JavaScript validating segments of the form as well as JavaScript producing an alert at the end of the function.
The idea is to have the functions is to validate the form so that, if you are over 18: you only need the first and last name fields filled out. (The content doesn't really matter so long as it works.) On the other hand however, if you are under 18, the function will need to validate guardian details as well.
Until somewhat recent changes were made however this worked fine, the problem is I left the project for several weeks so I don't know what changes were made to be able to undo them. Ideally the basic code wouldn't change too much, I'm looking for a quick fix or stop-gap measures that will have the same effect.
<html>
<head>
<meta charset="utf-8">
<title>Work Field Trip Registration</title>
<script type="text/javascript">
function HideReveal() {
if (document.getElementById("YesNo").selectedIndex == "1") {
document.getElementById("ifYes").style.display = "block";
Required();
//alert('1st Option Tested');
}
else if (document.getElementById("YesNo").selectedIndex == "0") {
document.getElementById("ifYes").style.display = "none";
Required();
//alert('2nd Option Tested');
}
}
function Required() {
if (document.getElementById("YesNo").selectedIndex == "1") {
AddRequirement();
//alert("Step1");
}
else {
NoRequirement();
//alert("Step2");
}
}
function NoRequirement() {
document.getElementById("GuardName").removeAttribute("required");
document.getElementById("GuardPhone").removeAttribute("required");
//alert("Step3");
}
function AddRequirement() {
document.forms("death")("GuardianName").setAttribute("required", "");
document.forms("death")("GuardianNumber").setAttribute("required", "");
//alert("Step4");
}
function validateForm() {
var a = document.forms("death")("GuardianName").value;
var b = document.forms("death")("GuardianNumber").value;
var c = document.forms("death")("FirstName").value;
var d = document.forms("death")("LastName").value;
if (document.getElementById("YesNo").selectedIndex == "1")
{
if (a == "" || b == "") {
alert("Please fill ALL required fields");
}
else {
alert("Registration Complete!");
}
}
else if (c == "" || d == "") {
alert("Please fill ALL required fields")
}
else {
alert("Registration Complete!")
}
}
</script>
</head>
<body>
<h2>Work Field Trip Registration!</h2>
<h4>Please enter your details.</h4>
<form name="death">
First Name:<br>
<input required type="text" name="FirstName"><br>
Last Name:<br>
<input required type="text" name="LastName"><br>
Gender:<br>
<select name="dMenu">
<option>Male</option>
<option>Female</option>
</select><br><br>
Are you under 18?
<select id="YesNo" onChange="HideReveal()" name="dMenu">
<option name="OptionNo" id="OptionNo" value="0">No</option>
<option name="OptionYes" id="OptionYes" value="1">Yes</option>
</select><br><br>
<div id="ifYes" style="display:none">
Please enter your Parent/Guardian's name:<br>
<input type="text" id="GuardName" name="GuardianName"><br>
Please enter your Parent/Guardian's phone number:<br>
<input type="text" id="GuardPhone" name="GuardianNumber"><br>
</div>
<input onClick="validateForm()" type="submit" value="Submit">
</form>
</body>
</html>
1) you don't need to call validate if you already set field to required. The browser will handle that for you.
2. I wonder why you used 'getElementbyId' in NoRequirement() but document.forms in AddRequirement().
In anycase here is a modified version of your code. cheers
<html>
<head>
<meta charset="utf-8">
<title>Work Field Trip Registration</title>
<script type="text/javascript">
function HideReveal() {
if (document.getElementById("YesNo").selectedIndex == "1") {
document.getElementById("ifYes").style.display = "block";
Required();
//alert('1st Option Tested');
}
else if (document.getElementById("YesNo").selectedIndex == "0") {
document.getElementById("ifYes").style.display = "none";
Required();
//alert('2nd Option Tested');
}
}
function Required() {
if (document.getElementById("YesNo").selectedIndex == "1") {
AddRequirement();
//alert("Step1");
}
else {
NoRequirement();
//alert("Step2");
}
}
function NoRequirement() {
document.getElementById("GuardName").removeAttribute("required");
document.getElementById("GuardPhone").removeAttribute("required");
//alert("Step3");
}
function AddRequirement() {
document.getElementById('GuardName').setAttribute("required","")
document.getElementById('GuardPhone').setAttribute("required","")
//alert("Step4");
}
</script>
</head>
<body>
<h2>Work Field Trip Registration!</h2>
<h4>Please enter your details.</h4>
<form name="death">
First Name:<br>
<input required type="text" name="FirstName"><br>
Last Name:<br>
<input required type="text" name="LastName"><br>
Gender:<br>
<select name="dMenu">
<option>Male</option>
<option>Female</option>
</select><br><br>
Are you under 18?
<select id="YesNo" onChange="HideReveal()" name="dMenu">
<option name="OptionNo" id="OptionNo" value="0">No</option>
<option name="OptionYes" id="OptionYes" value="1">Yes</option>
</select><br><br>
<div id="ifYes" style="display:none">
Please enter your Parent/Guardian's name:<br>
<input type="text" id="GuardName" name="GuardianName"><br>
Please enter your Parent/Guardian's phone number:<br>
<input type="text" id="GuardPhone" name="GuardianNumber"><br>
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>

Adding Span with Class to a input tag with Jquery

I am trying to add a Span after my Input that will have the class "error" and the text "test".
I've tried the append, and insertAfter methods. I can get the code to work on jsfiddle but I cannot get the code to work on my application.
I have put the HTML and JS/Jquery below. My end result would have a Span (with the class error) next to each input with the type text. I would then set a value for this span based on a validation loop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Zito - Lab 7</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="reservation.js" type="text/javascript"></script>
</head>
<body>
<h1>Reservation Request</h1>
<form action="response.html" method="get"
name="reservation_form" id="reservation_form">
<fieldset>
<legend>General Information</legend>
<label for="arrival_date">Arrival date:</label>
<input type="text" name="arrival_date" id="arrival_date" autofocus><br>
<label for="nights">Nights:</label>
<input type="text" name="nights" id="nights"><br>
<label>Adults:</label>
<select name="adults" id="adults">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<label>Children:</label>
<select name="children" id="children">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
</fieldset>
<fieldset>
<legend>Preferences</legend>
<label>Room type:</label>
<input type="radio" name="room" id="standard" class="left" checked>Standard
<input type="radio" name="room" id="business" class="left">Business
<input type="radio" name="room" id="suite" class="left last">Suite<br>
<label>Bed type:</label>
<input type="radio" name="bed" id="king" class="left" checked>King
<input type="radio" name="bed" id="double" class="left last">Double Double<br>
<input type="checkbox" name="smoking" id="smoking">Smoking<br>
</fieldset>
<fieldset>
<legend>Contact Information</legend>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email"><br>
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
</fieldset>
<input type="submit" id="submit" value="Submit Request"><br>
</form>
</body>
</html>
JS/JQuery
$(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
var phonePattern = /\b(\d{3})([-])(\d{3})([-])(\d{4})\b/;
var datePattern = /\b(0[1-9]|1[012])([/])(0[1-9]|1[0-9]|2[0-9]|3[01])([/])((20)\d\d)\b/;
$(":text").after("<span class='error'>*</span>");
$("#arrival_date").focus();
$("#reservation_form").submit(
function(event) {
var isValid = true;
// validate arrival date
var arrivalDate = $("#arrival_date").val();
if (arrivalDate == "") {
$("#arrival_date").next().text("This field is required");
isValid = false;
} else if (!datePattern.test(arrivalDate)) {
$("#arrival_date").next().text("Must be in the format 12/12/2012");
isValid = false;
} else {
$("#arrival_date").next().text("");
}
// validate nights
var nights = $("#nights").val();
if (nights == "") {
$("#nights").next().text("This field is required");
isValid = false;
} else if ((isNaN(parseInt(nights))) || (parseInt(nights) <=0)) {
$("#nights").next().text("This field must be a number and not zero");
isValid = false;
} else {
$("#nights").next().text("");
}
// validate name
var name = $("#name").val();
if (name == "") {
$("#name").next().text("This field is required");
isValid = false;
} else {
$("#name").next().text("");
}
// validate email
var email = $("#email").val();
if (email == "") {
$("#email").next().text("This field is required");
isValid = false;
} else if (!emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
// validate phone
var phone = $("#phone").val();
if (phone == "") {
$("#phone").next().text("This field is required");
isValid = false;
} else if (!phonePattern.test(phone) ) {
$("#phone").next().text("Must be in the format 999-999-9999");
isValid = false;
} else {
$("#phone").next().text("");
}
if (isValid == false) {
event.preventDefault();
$("#arrival_date").focus();
}
}
);
}); // end ready
Most easy way is to add a Div container around the form and just append the warning to that. To effectively append after an element you need to give it a class or id.
var email = $("#email"); //using class instead of input:text
var html = "<span class='error'>TEST!</span>"
email.after( html );
But I personally would like something like this better:
var generateError = function(){
var html = "<div id='error' style='top: 0; left:0; width:100%; height: 50px; background-color: red; text-allign: center; display:none; z-index: 100;'> ERROR!!</div>"
$(body).append( html );
}
var showError = function( text ){
var err = $("#error");
err.html( text );
err.show(500).delay(2000).hide(500);
}
Code is fairly self-explaining, but this will make two functions: generateError and showError.
generateError you need to call before you want to show the error, possibly when the page loads it will add a small header on top of all you other elements and will appear hidden.
showError uses a text argument with the error you want to show. Then it will set the text to the div and show it for two seconds.
This then is more what you are looking for?
$(document).ready(function () {
var input = $("input");
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
input.keypress(function (ele) {
// if regex.test( input ) === false
createErrors(ele.target);
})
});
var createErrors = function (ele) {
$('<span>TEST!</span>').insertAfter(ele);
$("#arrival_date").focus();
};
This works on keypress, that means the regex gets checked every time a key is pressed. It also passes the element where the user is typing as parameter, this means that you wont get errors for all input:text, but only for the ones where there is an error.
Updated Fiddle (still not perfect, but if its an school exercise this will help you to finish it :)

Categories