Javascript form validation not working in the browser properly - javascript

I am building a application using pure javascript approach that validates a registration form. The form has five controls: username, password and retype password fields, a checkbox that allows the user to toggle the password visibility and submit button.
I am having some issues trying to understand why my code is not working properly on the browse.
The error messages are not showing.
The button submit is not sending to the confirmation page " I've
tried constantly to solve it but no result".
The check password match is not working.
I hope I explained well.
Many thanks.
Here is the second HTML page for the form submission.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<section>
<p>Form Successfully Submitted</p>
</section>
</body>
</html>
Here is my javascript code CSS AND HTML.
function handleInvalidities(input) { // Takes input field as parameter
let errMsg = "";
if (!input.validity.paternMismatch) { // Check for wrong format
errMsg = "Invalid entry. Enter your details in the format shown.";
}
if (input.validity.valueMissing) {
errMsg = "Invalid entry. This field can not be blank. Please enter a value."; // Check for missing fields
}
return errMsg;
}
function displayInvalidities(errMsg, elem) {
let elemPos = document.getElementById(elem);
let errElem = document.createElement("span");
errElem.setAttribute("class", "error");
let errText = document.createTextNode(errMsg);
errElem.appendChild(errText);
elemPos.parentNode.insertBefore(errElem, elemPos.nextSibling);
}
function cleanUpErrors() {
let errors = document.getElementsByClassName("error");
for (let i = 0; i < errors.length; i++) {
errors[i].style.display = "none"; // Clear up existing error messages
}
}
function Toggle() {
var temp = document.getElementById("password");
if (temp.type === "password") {
temp.type = "text";
} else {
temp.type = "password";
}
}
function checkPasswordMatch (registerForm) {
let originalPassword = registerForm.password.value;
let retypedPassword = registerForm.retypedpassword.value;
if (originalPassword === retypedPassword) {
return true;
} else {
let passwordMatchError = document.getElementById("passwordmatcherror");
passwordMatchError.setAttribute("class", "error");
passwordMatchError.innerHTML = ("Passwords do not match. Please retype");
return false;
}
}
window.onload = () => {
let registerForm = document.getElementById("regsiterdetails"); // Get the form and add event listener to it
registerForm.addEventListener("submit",
(event) => {
if (!checkPasswordMatch(registerForm)) {
event.preventDefault(); // If no match stop form submitting
}
}, false);
}
body {
font-family: Verdana;
font-size: 0.75rem;
}
h1 {
font-size: 1.25rem;
}
h2 {
font-size: 1rem;
}
label {
display: block;
font-weight: bold;
margin: 0.25rem 0 0.25rem 0;
}
#showpasswordslabel {
display:inline;
}
#showpasswords {
width: 18px;
height: 18px;
}
.error {
width:15%;
min-width: 240px;
display: block;
padding: 0.5rem;
font-size: 0.75rem;
color: white;
background-color: #900;
margin: 0.5rem;
border: 2px solid transparent;
}
input:not(#showpasswords) {
width:15%;
min-width: 240px;
height: 10px;
padding: 10px 0 10px 10px;
margin: 0.5rem;
border: 2px solid transparent;
border-radius: 5px;
box-shadow: 2px 2px 2px #B2B2B2, -1px -1px 1px #292929;
position: relative;
}
button {
margin-top: 1rem;
border: none;
background: #3498db;
width: 80px;
height: 35px;
padding: 0;
margin-top: 16px;
cursor: pointer;
box-shadow: 1px 1px 1px #292929, -1px -1px 1px #B2B2B2;
border-radius: 5px;
transition: all .3s;
color: white;
font-weight: 700;
margin-left: 0.5rem;
}
button:hover {
background: #2980b9;
}
button:focus {
box-shadow: 1px 1px 1px #B2B2B2, -1px -1px 1px #292929;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<section>
<h1>Form: validated using Javascript</h1>
<p>Try entering the following:</p>
<ul>
<li>Password longer or shorter than 8 characters and/or without an uppercase, lowercase or a numeric.</li>
<li>Passwords that do not match</li>
</ul>
<h2>Register</h2>
<p>* = Required Field</p>
<div id="formcontainer">
<form id="regsiterdetails" action="fma_t3confirm.html" onsubmit="validateForm(event)"></form>
<div>
<label for="username">* Username:</label>
<input type="text" id="username" required>
</div>
<div>
<label for="password">* Password (Must be 8 characters and include one uppercase, one lowercase and one
numeric):</label>
<input type="password" id="password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,8}$" required>
<input type="checkbox" id="showpasswords" onclick="Toggle()">
<label id="showpasswordslabel" for="showpasswords">Show passwords</label>
</div>
<div>
<label for="retypedpassword">* Retype your password:</label>
<input type="password" id="retypedpassword">
<span id="passwordmatcherror"></span>
</div>
<div>
<button type="submit" id="registerButton">Register</button>
</div>
</form>
</div>
</section>
</body>
<script src="scripts/fma_t3.js"></script>
</html>

Related

How to submit an list when one of the list item is selected

hello i am creating a search bar that has auto complete feature can someone tell how to auto submit when one of the option is selected
some other possible solutions are autosubmit when the input field contains $
{i will add a $ swmbol in each of the array}
you can check the whole program on codepen by clicking here
https://codepen.io/simplyrajatgupta/pen/wvmXPJv
here is the codes
let suggestions = [
"Channel",
"CodingLab",
"CodingNepal",
"YouTube",
"YouTuber",
"YouTube Channel",
"Blogger",
"Bollywood",
"Vlogger",
"Vechiles",
"Facebook",
"Freelancer",
"Facebook Page",
"Designer",
"Developer",
"Web Designer",
"Web Developer",
"Login Form in HTML & CSS",
"How to learn HTML & CSS",
"How to learn JavaScript",
"How to become Freelancer",
"How to become Web Designer",
"How to start Gaming Channel",
"How to start YouTube Channel",
"What does HTML stands for?",
"What does CSS stands for?",
];
// getting all required elements
const searchWrapper = document.querySelector(".search-input");
const inputBox = searchWrapper.querySelector("input");
const suggBox = searchWrapper.querySelector(".autocom-box");
const icon = searchWrapper.querySelector(".icon");
let linkTag = searchWrapper.querySelector("a");
let webLink;
// if user press any key and release
inputBox.onkeyup = (e)=>{
let userData = e.target.value; //user enetered data
let emptyArray = [];
if(userData){
icon.onclick = ()=>{
webLink = `https://www.google.com/search?q=${userData}`;
linkTag.setAttribute("href", webLink);
linkTag.click();
}
emptyArray = suggestions.filter((data)=>{
//filtering array value and user characters to lowercase and return only those words which are start with user enetered chars
return data.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase());
});
emptyArray = emptyArray.map((data)=>{
// passing return data inside li tag
return data = `<li>${data}</li>`;
});
searchWrapper.classList.add("active"); //show autocomplete box
showSuggestions(emptyArray);
let allList = suggBox.querySelectorAll("li");
for (let i = 0; i < allList.length; i++) {
//adding onclick attribute in all li tag
allList[i].setAttribute("onclick", "select(this)");
}
}else{
searchWrapper.classList.remove("active"); //hide autocomplete box
}
}
function select(element){
let selectData = element.textContent;
inputBox.value = selectData;
icon.onclick = ()=>{
webLink = `https://www.google.com/search?q=${selectData}`;
linkTag.setAttribute("href", webLink);
linkTag.click();
}
searchWrapper.classList.remove("active");
}
function showSuggestions(list){
let listData;
if(!list.length){
userValue = inputBox.value;
listData = `<li>${userValue}</li>`;
}else{
listData = list.join('');
}
suggBox.innerHTML = listData;
}
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#200;300;400;500;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
body{
background: #644bff;
padding: 0 20px;
}
::selection{
color: #fff;
background: #664AFF;
}
.wrapper{
max-width: 450px;
margin: 150px auto;
}
.wrapper .search-input{
background: #fff;
width: 100%;
border-radius: 5px;
position: relative;
box-shadow: 0px 1px 5px 3px rgba(0,0,0,0.12);
}
.search-input input{
height: 55px;
width: 100%;
outline: none;
border: none;
border-radius: 5px;
padding: 0 60px 0 20px;
font-size: 18px;
box-shadow: 0px 1px 5px rgba(0,0,0,0.1);
}
.search-input.active input{
border-radius: 5px 5px 0 0;
}
.search-input .autocom-box{
padding: 0;
opacity: 0;
pointer-events: none;
max-height: 280px;
overflow-y: auto;
}
.search-input.active .autocom-box{
padding: 10px 8px;
opacity: 1;
pointer-events: auto;
}
.autocom-box li{
list-style: none;
padding: 8px 12px;
display: none;
width: 100%;
cursor: default;
border-radius: 3px;
}
.search-input.active .autocom-box li{
display: block;
}
.autocom-box li:hover{
background: #1bb361;
color: white;
}
.search-input .icon{
position: absolute;
right: 0px;
top: 0px;
height: 45px;
;
width: 45px;
text-align: center;
line-height: 45px;
font-size: 20px;
color: white;
cursor: pointer;
background: #1a74f2;
right: 5px;
top: 5px;
bottom: 5px;
border-radius: 5px;
}
.search-input
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Autocomplete Search Box | CodingNepal</title>
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
<form action="https://www.google.com/search?q=">
<div class="wrapper">
<div class="search-input">
<a href="" target="_blank" hidden></a>
<input type="text" id="ra"placeholder="Enter question or chapter...">
<div class="autocom-box">
<!-- here list are inserted from javascript -->
</div>
<div class="icon" id="ca"type="submit"><i class="fas fa-search"></i></div>
</div>
</div>
</form>
<script src="js/suggestions.js"></script>
<script src="js/script.js"></script>
<script>
var input = document.getElementById("ra");
input.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
document.getElementsByClassName("ca").click();
}
});
</script>
</body>
</html>
Instead write code for clicking search button, you can just call window.open('http://url-goes-here.com').
inputBox.onkeydown = (e) => {
let firstSuggestion = suggestions.filter(el =>
el.toLowerCase().includes(e.target.value.toLowerCase()))[0];
if((e.keyCode == 13) && firstSuggestion)
e.preventDefault();
window.open(`https://www.google.com/search?q=${firstSuggestion}`)
}
}
This function make input that matched with first suggestion auto-submitted when enter key pressed. If you wanna use this function, make sure you delete another function that also record enter key in input.
.onkeydown make any key pressed in inputBox will be 'record'. If the key pressed is enter (enter keycode = 13) and first suggestion exist (not null), so you will be redirect to google url + first suggestion query.
firstSuggestion in here, defined as filtered suggestion list, which only include suggestion that contains character of your search query.

I have a problem with my div when I write in the text area and hit save nothing is show up

I have a problem with my div when I write in the text area and hit save nothing is show up. I have a problem with my div when I write in the text area and hit save nothing is show up
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="Go from idea to action in seconds with wesam to do list">
<title>wesam list to do</title>
<script>
function input() {
var name = document.getElementById("text").Value
document.getElementById("output").innerHTML = name;
}
</script>
<style>
#b {
background-color: red;
}
#output {
width: 100%;
height: 200px;
background-color: black;
color: black;
}
</style>
</head>
<body>
<form>
<h1> Add your tasks </h1>
<textarea id="text"></textarea>
<button onClick="input()" id=" b " type="button "> save</button>
<div id="output"></div>
</body>
Try this. There were a few issues with this code. I added comments to the changes.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="Go from idea to action in seconds with wesam to do list">
<title>wesam list to do</title>
<script>
function input(event) {
//added preventDefault() to keep the page from reloading
event.preventDefault();
//changed Value to value - watch your case
var name = document.getElementById("text").value;
document.getElementById("output").innerHTML = name;
}
</script>
<style>
#b {
background-color: red;
}
#output {
width: 100%;
height: 200px;
background-color: black;
/*changed the text color from black to white so you can see when the output is added*/
color: white;
}
</style>
</head>
<body>
<form>
<h1> Add your tasks </h1>
<textarea id="text"></textarea>
<button onClick="input(event)" id="b" type="button"> save</button>
<div id="output"></div>
</form>
</body>
</html>
Cheers!
Your output element has both a black background, and black text, so you won't see anything change.
You were missing a </form> tag.
It looks like you're trying to create a list of tasks, and each time you add a new task, and click "save" it adds a new task under the proceeding ones.
Here's an updated example that uses more modern JS methods that you might find useful. Links to the relevant documentation are at the bottom of the post.
// First we cache all our elements
const task = document.querySelector('textarea');
const list = document.querySelector('ul');
const button = document.querySelector('button');
// Instead of inline JS we add an event listener to
// the cached button element.
button.addEventListener('click', handleClick, false);
// `focus` the cursor in the textarea
task.focus();
function handleClick() {
// We create a new list item
const item = `<li>${task.value}</li>`;
// We add that to the list
list.insertAdjacentHTML('beforeend', item);
// Reset the textarea value
task.value = '';
// And refocus on it so we don't have to
// manually click in it to write a new task
task.focus();
}
button { background-color: red; color: white; }
<form>
<h3>Add your tasks</h3>
<textarea></textarea>
<button type="button">Save task</button>
</form>
<ul></ul>
Addition documentation
querySelector
Template/string literals
insertAdjacentHTML
addEventListener
There are couple problem:
You didn't close the form tag in HTML
you write the first letter of value as capital in input function
And you may did not look but your button background color is not coming that is because there is spaces inside the id in HTML just remove those and you're good to go.
And make a paragraph inside the output div and give him the id of output and than stor that into a variable and do o.innerText o is you output paragraph = i.value i is your input
I have added some features to to your application if you want to copy it i do not mined -
// ES6 Syntax
const render = () =>{
// Getting the value from HTML DOM to inputEl variable
const inputEl = document.getElementById('text');
// Getting the output paragraph from HTML DOM and storig it into output
const outputEl = document.getElementById('output-text');
// Rendering the inputEL value into outputEl
outputEl.textContent = inputEl.value;
}
// ES5-- Syntax
function renderES(){
// Getting the value from HTML DOM to inputEl variable
const inputEl = document.getElementById('text');
// Getting the output paragraph from HTML DOM and storig it into output
const outputEl = document.getElementById('output-text');
// Rendering the inputEL value into outputEl
outputEl.textContent = inputEl.value;
}
#import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');
:root{
--primary-color: rgb(26, 26, 26);
--secondary-color: white;
--font-family: Nunito, sans-serif;
--box-shadow: rgb(0 0 0) 1px 1px 3px 0px inset, rgb(48 48 48 / 50%) -1px -1px 3px 1px inset;;
--all-transition:transform ease-in-out 0.3s 0s;
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
font-family: var(--font-family);
}
.main-content{
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container{
border-radius: 10px;
box-shadow: var(--box-shadow);
width: 85%;
height: 270px;
display: flex;
justify-content: space-between;
align-items: center;
background-color: var(--primary-color);
flex-direction: column;
}
.container>h1{
margin-top: 15px;
color: var(--secondary-color);
text-transform: uppercase;
}
form{
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
padding: 5px;
width: 100%;
height: 75%;
}
form>textarea{
width: 95%;
height: 30%;
background-color: var(--primary-color);
border: none;
border-radius: 10px;
box-shadow: var(--box-shadow);
padding: 15px;
color: var(--secondary-color);
}
#output{
width: 95%;
height: 40%;
background-color: var(--primary-color);
box-shadow: var(--box-shadow);
color: var(--secondary-color);
padding: 10px;
}
form>button{
background-color: var(--primary-color);
box-shadow: var(--box-shadow);
width: 95%;
height: 30px;
border-radius: 10px;
border: none;
font-weight: bold;
margin-bottom: 10px;
color:var(--secondary-color);
transition: var(--all-transition);
cursor: pointer;
}
/* NTH CHILD */
form>textarea::placeholder{
color: var(--secondary-color);
}
/* Animations */
form>button:hover{
transform: scale(1.02)
}
form>button:active{
border: 1px solid var(--secondary-color);
}
<!doctype HTML>
<html>
<head>
<title>codedamn HTML Playground</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<div class="main-content">
<div class="container">
<h1> Add your tasks </h1>
<form>
<textarea id="text" placeholder="Enter you task here.."></textarea>
<div id="output">
<p id="output-text"></p>
</div>
<button
type="button"
id="addtask-btn"
onclick="render()">
Save
</button>
<form>
</div>
</div>
<script src="/script.js"></script>
</body>
</html>
It seems that you haven't ended the
<form>
tag

Separate Functions For Finding The Area and Perimeter of a Rectangle Part II

So, thanks to a fantastic person here Barmar, I completed my code correctly with user input instead of how I made it initially, which was giving the answer of Area and Perimeter at the same time.
But I am being told to separate this into two functions. Essentially, create separate tasks for the Area and Perimeter calculations and pass the length and width parameters.
It works flawlessly and I am just unsure how to separate this wonderful function into several more...
Below is my codepen and code for it if anyone has any suggestions.
With the help of Barmar, I thought I had done a great job with this, but now I am being challenged one last time before midnight to make separate functions from them. Any advice or pointers would be helpful. Thank you.
CodePen Link
Code Snippet:
function controller() {
var type = document.getElementById("apBox").value;
var length = document.getElementById("lengthBox").value;
var width = document.getElementById("widthBox").value;
var mainSolution = document.getElementById("message");
var answer;
var label;
if (type == "a" || type == "A") {
answer = length * width;
label = 'Area';
} else if (type == "p" || type == "P") {
answer = 2 * length + 2 * width;
label = 'Perimiter';
} else {
mainSolution.innerText = "Invalid. Must Enter 'A' or 'P'";
return;
}
if (length.length > 0 && width.length > 0) {
if (!isNaN(answer)) {
mainSolution.innerHTML = `${label} =&nbsp ${answer}`;
}
} else {
mainSolution.innerHTML = "";
}
}
function clearText() {
document.getElementById("message").innerHTML = ("<br>");
document.getElementById("apBox").value = "";
document.getElementById("lengthBox").value = "";
document.getElementById("widthBox").value = "";
}
#main {
background-color: #455A6F;
border-radius: 3px;
padding: 10px;
}
#header {
background-color: #292A2B;
border-radius: 3px;
padding: 10px;
}
body {
text-align: center;
font-family: Montserrat;
color: #fff;
}
a {
color: rgb(27, 157, 218);
}
.btn1,
.btn2 {
background-color: rgba(52, 139, 221, 0.699);
border: #303436;
font-family: Montserrat;
font-size: 12px;
color: #fff;
letter-spacing: 2px;
padding: 5px;
font-size: 16px;
font-weight: bold;
border-radius: 5px;
line-height: 3;
text-decoration: none;
box-shadow: 0 0 4px black;
text-shadow: 0 1px 0 black;
margin-top: 1em;
margin-bottom: 1em;
margin-left: 1em;
margin-right: 1em;
}
h1,
h2,
h3,
h4,
h5,
h6 {
text-shadow: 1px;
text-transform: capitalize;
text-align: center;
}
/* This is a custom snippet I made, so the footer always stays at the bottom of the page */
footer {
position: absolute;
right: 0;
bottom: 0;
left: 0;
padding: 2em;
background-color: transparent;
text-align: center;
border-color: rgb(0, 0, 0);
border-radius: 18px;
padding: 12px;
margin-top: 30em;
margin-bottom: 1em;
}
.description {
font-style: italic;
}
form {
border-radius: 25px;
padding: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="styles.css">
<meta name="description" content="Program 9 Assignment, IS30A, Area of a Rectangle">
<title>Program 9</title>
</head>
<!-- HTML Body -->
<body>
<div id="main">
<div id="header">
<h1>Program 9</h1>
<h5>Area or Perimeter</h5>
<h6>of a Rectangle</h6>
</div>
<!-- Main Form & Inputs For User Interaction -->
<form id="myForm">
<form id="myForm">
<label for="userInput1">Enter A for Area or P for Perimeter:</label><br><br>
<input type="text" id="apBox">
<br><br>
<label for="userInput2">Length:</label><br><br>
<input type="text" id="lengthBox"><br><br>
<label for="userInput3">Width:</label><br><br>
<input type="text" id="widthBox">
</form>
<!-- Empty Field & Message For User Who Interacted as well as Output: -->
<p id="demo">Output: </p>
<p id="message"> <br> </p>
<!-- Buttons For Submit & Clear Fields Above -->
<button class="btn1" type="button" onClick="controller()">Submit</button>
<button class="btn2" type="button" onClick="clearText()">Clear</button>
</div>
<script type="text/javascript" src="controller.js"></script>
</body>
<!-- End HTML -->
</html>
it's actually quite simple to make these their own functions. Your javascript will look like this:
function controller() {
var type = document.getElementById("apBox").value;
var length = document.getElementById("lengthBox").value;
var width = document.getElementById("widthBox").value;
var mainSolution = document.getElementById("message");
var answer;
var label;
if (type == "a" || type == "A") {
answer = Area(length, width);
label = 'Area';
} else if (type == "p" || type == "P") {
answer = Perimiter(length, width);
label = 'Perimiter';
} else {
mainSolution.innerText = "Invalid. Must Enter 'A' or 'P'";
return;
}
if (length.length > 0 && width.length > 0) {
if (!isNaN(answer)) {
mainSolution.innerHTML = `${label} =&nbsp ${answer}`;
}
} else {
mainSolution.innerHTML = "";
}
}
function Perimiter(length, width){
return length * 2 + width * 2
}
function Area(length, width){
return length * width
}
function clearText() {
document.getElementById("message").innerHTML = ("<br>");
document.getElementById("apBox").value = "";
document.getElementById("lengthBox").value = "";
document.getElementById("widthBox").value = "";
}

How to find the problem in this HTML form that uses AJAX requests but fails with textarea

I am trying to receive customer feedback and transfer that data to Google Forms with AJAX requests, but my form keeps failing to work with textarea. How do I do this properly, since I am not sure where the problem lies.
[NOTE: The form works perfectly without textarea, but I figured I need textarea to receive a large user input, ex: descriptions of answers]
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Dosis|Ubuntu+Mono|Quicksand|Josefin+Sans|Montserrat|Francois+One|Marvel" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body style="background:white; font-family:Montserrat;">
<h1>Feedback/Review</h1>
<p>The Team would be happy to hear from you about our services! Leave feedback or a review using the form below.</p>
<form id="form" target="_self" onsubmit="return postToGoogle();" action="" autocomplete="off">
<label id = "namelabel">Name:</label><label id = "emaillabel">Email: </label><br>
<input id="nameField" name="entry.1803640717" placeholder="First / Last Name" type="text" required>
<input id="emailField" name="entry.63463603" placeholder="Enter Your Email" type="email" required><br><br>
<label id = "relationlabel">Relation:</label><label id = "choicelabel">Why are you contacting us?</label><br>
<input id="mobField" name="entry.1793553898" placeholder="Relation to [BUSINESS] (EX: customer)" type="text" required>
<select id="cinema" name="entry.26162353" placeholder="Select Cinema" required>
<option value="">Choose an Option</option>
<option value="">Question about Prices</option>
<option value="">Had Issues With The Process</option>
<option value="">Feedback for great work</option>
<option value="">Other Option/Not Listed</option>
</select><br><br>
<label>Comment Here:</label><br>
<textarea id="explainfield" name="entry.1396765295" rows = "10" cols = "128" required></textarea>
<button id="send" type="submit" class="common_btn">Submit Form</button>
</form>
<h3 id="success-msg" style="text-align: center !important; margin-top:190px !important; display:none; color:#fff"> Your Request has been recieved!</h3>
<style>
body {font-family: Arial, Helvetica, sans-serif; margin-left: 330px; margin-right: 330px;}
form {border: 3px solid #f1f1f1; font-family: QuickSand;}
input[type=text], input[type=email], select {
width: 49%;
font-size:20px;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: maroon;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 98.5%;
}
button:hover {
opacity: 0.4;
}
.cancelbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
.imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
}
img.avatar {
width: 20%;
border-radius: 50%;
}
.container {
padding: 16px;
}
span.psw {
float: right;
padding-top: 16px;
}
#namelabel, #relationlabel {
margin-right: 30px;
}
#emaillabel {
margin-left: 385px;
}
#choicelabel {
margin-left: 370px;
}
/* Change styles for span and cancel button on extra small screens */
#media screen and (max-width: 300px) {
span.psw {
display: block;
float: none;
}
.cancelbtn {
width: 100%;
}
}
</style>
<script>
function postToGoogle() {
var field1 = $("#nameField").val();
var field2 = $("#emailField").val();
var field3 = $("#mobField").val();
var field4 = $("#cinema option:selected").text();
var field5 = $("#explainfield").val();
if(field1 == ""){
alert('Please Fill Your Name');
document.getElementById("nameField").focus();
return false;
}
if(field2 == ""){
alert('Please Fill Your Email');
document.getElementById("emailField").focus();
return false;
}
if(field3 == "" || field3.length < 1){
alert('Please Fill Your Mobile Number');
document.getElementById("mobField").focus();
return false;
}
if (field5 == "" || field5.length < 1 {
alert('Please comment down below');
document.getElementById("explainfield").focus();
return false;
}
$.ajax({
url: "https://docs.google.com/forms/d/e/1FAIpQLSdTNZewdXbyY51ueD9OEBi4Cca3JkVT1p4CykMSPyfzRpWHyQ/formResponse?",
data: {"entry.1803640717": field1, "entry.63463603": field2, "entry.1793553898": field3, "entry.26162353": field4, "entry.1396765295": field5},
type: "POST",
dataType: "xml",
success: function(d)
{
},
error: function(x, y, z)
{
$('#success-msg').show();
$('#form').hide();
}
});
return false;
}
</script>
</body>
</html>
I don't know if it will solve your problem but you have forgotten a closing bracket :
if (field5 == "" || field5.length < 1 {
should be
if (field5 == "" || field5.length < 1) {

Responsive HTML form

I am using the following css code:
html {
background: #2B2B2B url(images/bg.gif) repeat;
}
body {
max-width: 1000px;
margin: 0px auto;
font-family: sans-serif;
margin: 0 auto;
}
header,
footer,
aside {
display: block;
}
h1 {
text-align: center;
color: rgba(0, 0, 0, 0.6);
text-shadow: 2px 8px 6px rgba(0, 0, 0, 0.2), 0px -5px 35px rgba(255, 255, 255, 0.3);
text-decoration: underline;
}
label {
display: block;
}
fieldset {
border: 0px dotted red;
width: 400px;
margin: 0 auto;
}
input,
select {
width: 400px;
height: 30px;
border-radius: 5px;
padding-left: 10px;
font-size: 14px;
}
select {
line-height: 30px;
background: #f4f4f4;
}
button {
font-size: 14px;
padding: 5px;
background: #333333;
color: #FFFCEC;
float: right;
width: 100px;
}
button:hover {
font-size: 16px;
}
#edit {
background: #DC5B21;
}
#delete {} #course,
#name,
#profesor,
#subject {
background: #ABDCD6;
}
label {
font-size: 15px;
font-weight: bold;
color: #282827;
}
table {
border-spacing: 0.5rem;
border-collapse: collapse;
margin: 0 auto;
background: #ABDCD6;
}
th {
background: #E9633B;
}
th,
td {
border: 2px solid black;
padding: 10px;
}
td {
font-weight: bold;
font-style: oblique;
}
tr:nth-child(even) {
background: #ABDCD6
}
tr:nth-child(odd) {
background: #DCD8CF
}
.container {
width: 1000px;
margin: 0 auto;
}
.headerbar {
width: 988px;
float: left;
}
.headerbar.top {
background: linear-gradient(45deg, rgba(255, 102, 13, 1) 3%, rgba(255, 109, 22, 1) 32%, rgba(255, 121, 38, 1) 77%, rgba(255, 121, 38, 1) 100%);
min-height: 100px;
border-radius: 19px 30px 0px 0px;
box-shadow: #938D94 7px 7px 5px;
}
.headerbar.bottom {
background: linear-gradient(45deg, rgba(255, 102, 13, 1) 3%, rgba(255, 109, 22, 1) 32%, rgba(255, 121, 38, 1) 77%, rgba(255, 121, 38, 1) 100%);
min-height: 60px;
border-radius: 25px;
border-radius: 0px 0px 37px 34px;
box-shadow: #938D94 7px 1px 5px;
}
.leftbar {
width: 50%;
background: #EB593C;
min-height: 605px;
float: left;
border-radius: 4px;
border: 3px dashed #282827;
}
.rightbar {
width: 47%;
background: #221E1D;
min-height: 595px;
float: left;
padding: 5px;
border: 2px solid #EB593C;
box-shadow: #938D94 5px 5px 5px;
}
#submit,
#clear {
border-radius: 25px;
}
input:focus {
border: 1px solid #FF9933;
}
#media screen and (max-width: 700px) {
.leftbar,
.rightbar {
float: none;
}
.headerbar.top h1 {
margin-left: 50px;
text-align: center;
float: left;
}
and here is my HTML page very simple
<!DOCTYPE html>
<html>
<head>
<title>My web app</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="mystyle2.css" rel="stylesheet"/>
<script>
var studentsArray = [];
var selectedIndex = -1;
function init() {
document.getElementById("tablerows").innerHTML = "";
if (localStorage.studentsRecord) {
studentsArray = JSON.parse(localStorage.studentsRecord);
for (var i = 0; i < studentsArray.length; i++) {
prepareTableCell(i, studentsArray[i].course, studentsArray[i].name, studentsArray[i].profesor, studentsArray[i].subject);
}
}
}
function onRegisterPressed() {
if(validate()){
var course = document.getElementById("course").value;
var name = document.getElementById("name").value;
var profesor = document.getElementById("profesor").value;
var subject = document.getElementById("subject").value;
var stuObj = {course: course, name: name, profesor: profesor, subject: subject};
if (selectedIndex === -1) {
studentsArray.push(stuObj);
} else {
studentsArray.splice(selectedIndex, 1, stuObj);
}
localStorage.studentsRecord = JSON.stringify(studentsArray);
init();
onClarPressed();
}else{
}
}
function prepareTableCell(index, course, name, profesor, subject) {
var table = document.getElementById("tablerows");
var row = table.insertRow();
var courseCell = row.insertCell(0);
var nameCell = row.insertCell(1);
var profesorCell = row.insertCell(2);
var subjectCell = row.insertCell(3);
var actionCell = row.insertCell(4);
courseCell.innerHTML = course;
nameCell.innerHTML = name;
profesorCell.innerHTML = profesor;
subjectCell.innerHTML = subject;
actionCell.innerHTML = '<button id="edit" onclick="onEditPressed(' + index + ')">Edit</button><br/><button id="delete" onclick="deleteTableRow(' + index + ')">Delete</button>';
}
function deleteTableRow(index) {
studentsArray.splice(index, 1);
localStorage.studentsRecord = JSON.stringify(studentsArray);
init();
}
function onClarPressed() {
selectedIndex = -1;
document.getElementById("course").value = "";
document.getElementById("name").value = "";
document.getElementById("profesor").value = "";
document.getElementById("subject").value = "Math";
document.getElementById("submit").innerHTML = "Register";
}
function onEditPressed(index) {
selectedIndex = index;
var stuObj = studentsArray[index];
document.getElementById("course").value = stuObj.course;
document.getElementById("name").value = stuObj.name;
document.getElementById("profesor").value = stuObj.profesor;
document.getElementById("subject").value = stuObj.subject;
document.getElementById("submit").innerHTML = "Update";
}
function validate(){
var errors = [];
var re = /^[\w]+$/;
var id = document.getElementById("course");
if(id.value==="" ){
errors.push("Course name is empty");
}else if(id.value.length<3){
errors.push("Course name is to shoort");
}else if(!re.test(id.value)){
errors.push("Input contains invalid characters");
}
var name = document.getElementById("name");
var regEx = /^[a-zA-Z ]+$/;
if(name.value===""){
errors.push("Name cannot be empty");
}else if(!regEx.test(name.value)){
errors.push("Name contains invalid characters");
}
var profesor = document.getElementById("profesor");
if(profesor.value===""){
errors.push("Professor field cannot be empty");
}else if(!regEx.test(profesor.value)){
errors.push("Professor field contains invalid characters");
}
if(errors.length>0){
var message = "ERRORS:\n\n";
for(var i = 0;i<errors.length;i++){
message+=errors[i]+"\n";
}
alert(message);
return false;
}
return true;
}
</script>
</head>
<body onload="init()">
<header class="headerbar top"><h1>ITEC3506: Assignment#2</h1></header>
<aside class="leftbar">
<div>
<fieldset>
<label for="course"><span>Course Name</span></label>
<input type="text" placeholder="enter name of course" id="course">
</fieldset>
<fieldset>
<label for="name">Your Name</label>
<input type="text" placeholder="enter your name" id="name">
</fieldset>
<fieldset>
<label for="profesor">Course Professor</label>
<input type="text" placeholder="enter course Professor" id="profesor">
</fieldset>
<fieldset>
<label for="subject">Subject</label>
<select id="subject">
<option value="Math">Math</option>
<option value="Physics">Physics</option>
<option value="Chemistry">Chemistry</option>
<option value="English">English</option>
<option value="CS">CS</option>
</select>
</fieldset>
<fieldset>
<label for="submit"> </label>
<button id="submit" onclick="onRegisterPressed()">Submit</button>
<button id="clear" onclick="onClarPressed()">Clear</button>
</fieldset>
</div>
</aside>
<aside class="rightbar">
<table id="regtable">
<thead>
<tr>
<th>Course</th>
<th>Student</th>
<th>Professor</th>
<th>Subject</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tablerows">
</tbody>
</table>
</aside>
<footer class="headerbar bottom"></footer>
</div>
</body>
</html>
My question is how can I transform this code into a responsive site.
Everything is resizing normally, except I cannot seem to resize my table and form. Could somebody help me?
A few things going on here.
First, you don't have a set width on a few of your fields, so change:
fieldset{
border: 0px dotted red;
width: 400px;
margin: 0 auto;
}
to:
fieldset{
border: 0px dotted red;
width: 400px;
margin: 0 auto;
max-width: 100%;
}
Also change .headerbar from width: 988px; to width: 100%;.
For responsive frameworks, you need to ensure that you never have a set a fixed width without ensuring there is a max-width attached to it, otherwise your content size will never drop below the size of your fixed width.
Second, I noticed the following:
.leftbar{
width: 50%;
background: #EB593C;
min-height: 605px;
float: left;
border-radius: 4px;
border: 3px dashed #282827;
}
You didn't specifically call this out, but when I check your code in a smaller view, I notice that your width: 50%; is causing the backgrounds to look off, which does not seem to be your intention. I would recommend adding .leftbar { width: 100%; } as well as .rightbar { width: 100%; } inside of #media screen and (max-width:700px){
That just leaves the table. Tables do not automatically break down, so are generally not something we want to use when developing a responsive site, but of course sometimes there is no getting around this.
There are a few ways to tackle the issue with the table. One is to set the table to display:block; and apply overflow-x: scroll; to it inside of your #media screen and (max-width:700px){, which will allow the user to scroll left/right when viewing it from smaller screens. Another is to use one of the various Javascript plugins that can achieve this.
Hope this helps get you on the right track. Best of luck!
Do not set width for these
input,select{/*width: 400px;*/}
fieldset{/*width: 400px;*/}
If you are setting width obviously you cannot obtain a responsive layout

Categories

Resources