I need to call a function which styles the JavaScript alerts, from another JavaScript function which outputs an alert and validation.
But after adding styled function, it doesn't either style or validate data.
function styledAlert() {
this.render = function(messageToDisplay) {
var winH = window.innerHeight;
var winW = window.innerWidth;
var divW = document.getElementById("dialogBox").offsetWidth;
var dialogBoxOverLay = document.getElementById('dialogBoxOverLay');
var dialogBox = document.getElementById('dialogBox');
dialogBoxOverLay.style.display = "block";
dialogBoxOverLay.style.height = winH + "px";
dialogBox.style.left = ((winW - divW) * 0.5) + "px";
dialogBox.style.top = "200px";
dialogBox.style.display = "block";
document.getElementById('dialogBoxBody').innerHTML = messageToDisplay;
}
this.ok = function() {
document.getElementById('dialogBoxOverLay').style.display = "none";
document.getElementById('dialogBox').style.display = "none";
}
}
function signupDataValidation() {
var password = document.forms["signupForm"]["password"].value;
var confirmPassword = document.forms["signupForm"]["confirmPassword"].value;
if (password == confirmPassword) {
return true;
} else {
var sAlert = new styledAlert();
sAlert.render("Password confirmation doesn't match Password.");
return false;
}
}
#dialogBoxOverLay {
display: none;
opacity: 0.8;
position: fixed;
top: 0px left: 0px;
width: 100%;
z-index: 10;
}
#dialogBox {
display: none;
position: fixed;
z-index: 10;
}
#dialogBox > div {
display: table;
}
<body>
<div id="dialogBoxOverLay"></div>
<div id="dialogBox">
<div>
<table>
<tr>
<td id="dialogBoxBody"></td>
</tr>
<tr>
<td id="dialogBoxButton">
<button type="button" id="OkButton" onclick="sAlert.ok()">OK</button>
</td>
</tr>
</table>
</div>
</div>
<form id="signupForm" name="signupForm" onsubmit="return signupDataValidation()">
<input id="password" name="password" type="password" required/>
<input id="confirmPassword" name="confirmPassword" type="password" required/>
<button id="submitBtn" type="submit">Sign Up</button>
</form>
</body>
Related
JSFiddle: https://jsfiddle.net/5k38svc9/1/
I have a button. When clicked, a form is appended to the document. That works fine. However I also need the button to change its text, but can't achieve it:
<div class = "video-row">
<div class="video-buttons">
<div class="add-button green-button light-button">Add comedian to favourites</div>
<form style="display:none" id = "the-form" action="/login" method="post">
<h2 class="form-title">Login</h2>
<input class="form-input" type="text" placeholder="username" name="username">
<button class = "login light-button" type="submit">Send</button>
</form>
</div>
var addForm = function() {
var element = document.getElementById("the-form");
element.style.display = "block";
var button = $(event.target);
button.innerHTML = "Hide form";
}
var elements = document.getElementsByClassName("add-button");
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', addForm, false);
}
Any help is appreaciated.
Just change addForm to this:
var addForm = function(event) {
var element = document.getElementById("the-form");
element.style.display = "block";
var button = event.target;
button.innerText = "Hide form";
}
Basically in the snippet you don't have jQuery so you can't use it, also you are not passing event object to the event handler addForm, finally I used .innerText() instead of innerHTML() since you are replacing the text only.
here is a working snippet:
var addForm = function(event) {
var element = document.getElementById("the-form");
element.style.display = "block";
var button = event.target;
button.innerText = "Hide form";
}
var elements = document.getElementsByClassName("add-button");
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', addForm, false);
}
.video-row {
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
}
.video-buttons {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.light-button {
padding: 10px;
background-color: green;
border-radius: 25px;
cursor:pointer;
}
<div class = "video-row">
<div class="video-buttons">
<div class="add-button green-button light-button">Add comedian to favourites</div>
<form style="display:none" id = "the-form" action="/login" method="post">
<h2 class="form-title">Login</h2>
<input class="form-input" type="text" placeholder="username" name="username">
<button class = "login light-button" type="submit">Send</button>
</form>
</div>
The following solution may help your cause:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunc()" id="myBtn">Press this Button</button>
<p id="demo"></p>
<script>
function myFunc() {
var x = document.getElementById("myBtn").textContent;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Still weeks into Javascript class it was a short fast pace class and I have this final project that has three class of orders with 3 options to chose from. All are radio type with amounts. There is no quantities listed nor is there tax or subtotal. The Total box should have a running balance and will clear when the Clear button is clicked.
This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript - Unit 2 Summary</title>
<link href="unit2-summary.css" rel="stylesheet" type="text/css"></link>
<script type="text/javascript">
/*function swap()
{
var left = $('#leftWrapper').html();
var right = $('#rightWrapper').html();
$('#leftwrapper').html(left);
$('#rightWrapper').html(right);
return false;
}*/
function doClear()
{
document.computerForm.totalSystemPrice.value = "";
document.ComputerForm.yourName.value = "";
document.ComputerForm.yourAddress.value = "";
document.ComputerForm.yourAddress2.value = "";
document.ComputerForm.yourCityStateZip.value = "";
document.ComputerForm.yourPhone.value = "";
document.ComputerForm.yourEmail.value = "";
document.ComputerForm.computerCase[0].checked = false;
document.ComputerForm.computerCase[1].checked = false;
document.ComputerForm.computerCase[2].checked = false;
document.ComputerForm.computerMonitor[0].checked = false;
document.ComputerForm.computerMonitor[1].checked = false;
document.ComputerForm.computerMonitor[2].checked = false;
document.ComputerForm.computerPrinter[0].checked = false;
document.ComputerForm.computerPrinter[1].checked = false;
document.ComputerForm.computerPrinter[2].checked = false;
return;
}
function doSubmit()
{
if (validateText() == false)
{
alert("Required Data Missing - Please Complete");
return;
}
if (validateRadio() == false)
{
alert("Required Order Data Missing - Please Complete");
return;
}
alert("Your Order has been placed.");
return;
}
function validateText()
{
var yourName = document.ComputerForm.yourName.value;
if (yourName.length == 0) return false;
var yourAddress = document.computerForm.yourAddress.value;
if (yourAddress.length == 0) return false;
var yourCityStateZip = document.ComputerForm.yourCityStateZip.value;
if (yourCityStateZip.length == 0) return false;
var yourPhone = document.ComputerForm.yourPhone.value;
if (yourPhone == 0) return false;
var yourEmail = document.ComputerForm.yourEmail.value;
if (yourEmail == 0) return false;
return true;
}
function validateRadio()
{
if (document.ComputerForm.computerCase[0].checked) return true;
if (document.ComputerForm.computerCase[1].checked) return true;
if (document.ComputerForm.computerCase[2].checked) return true;
if (document.ComputerForm.computerMonitor[0].checked) return true;
if (document.ComputerForm.computerMonitor[1].checked) return true;
if (document.ComputerForm.computerMonitor[2].checked) return true;
if (document.ComputerForm.computerPrinter[0].checked) return true;
if (document.ComputerForm.computerPrinter[1].checked) return true;
if (document.ComputerForm.computerPrinter[2].checked) return true;
}
function getTotal()
{
var computerPrice()
document.getElementById('totalPrice').value.innerHTML = "Total Computer Price $"
}
function startup()
{
var imgArray = new Array(3);
var index = 0;
imgArray[0] = new Image;
imgArray[0].src = "ComputerCase.jpg";
imgArray[1] = new Image;
imgArray[1].src = "ComputerMonitor.jpg";
imgArray[2] = new Image;
imgArray[2].src = "ComputerPrinter.jpg";
return;
}
</script>
</head>
<body>
<form name="ComputerForm">
<h1 align="center">Comupter System Order Form</h1>
<div id="container" font="courier" size="10">
<div id="left"><div id ="leftWrapper" class="wrapper">
<p><p></p>
<div class="gallery">
<a target="_blank" href="ComputerCase.jpg">
<img src="ComputerCase.jpg">
</a>
</div>
<h4>Computer Case Style:</h4>
<input name="computerCase" type="radio" onClick="calculateTotal()" />Desktop Case ($500.00)<br />
<input name="computerCase" type="radio" onClick="calculateTotal()" />Mini-Tower Case ($600.00)<br />
<input name="computerCase" type="radio" onClick="calculateTotal()" />Full Tower Case ($700.00)<br />
<p></p>
<div class="gallery">
<a target="_blank" href="ComputerMonitor.jpg">
<img src="ComputerMonitor.jpg">
</a>
</div>
<h4>Computer Monitors</h4>
<input name="computerMonitor" type="radio" onClick="calculateTotal()" />17" LCD Flat Screen ($250.00)<br />
<input name="computerMonitor" type="radio" onClick="calculateTotal()" />19" LCD Flat Screen ($300.00)<br />
<input name="computerMonitor" type="radio" onClick="calculateTotal()" />21" LCD Flat Screen ($350.00)<br />
<p></p>
<div class="gallery">
<a target="_blank" href="ComputerPrinter.jpg">
<img src="ComputerPrinter.jpg"></a>
</a>
</div>
<h4>Computer Printers</h4>
<input name="computerPrinter" type="radio" onClick="calculateTotal()" />Inkjet Printer ($100.00)<br />
<input name="computerPrinter" type="radio" onClick="calculateTotal()" />Laser Printer ($250.00)<br />
<input name="computerPrinter" type="radio" onClick="calculateTotal()" />Color Laser Printer ($350.00)<br />
</p><p></p>
</div>
</div>
<div id="right"><div id="rightWrapper" class="wrapper">
<br><br>
<p>Total System Price: $
<input name="totalSystemPrice" size="14px" type="text" id="totalPrice" class="totalPrice" readonly>
</p>
<br><br>
<hr />
<p></p><p></p><p></p>
Name: <input name="yourName" size="50" type="text"><br />
Address: <input name="yourAddress" size="50" type="text"><br />
<input name="yourAddress2" size="50" type="text"><br />
City, State, Zip: <input name="yourCityStateZip" size="50" type="text"><br />
Phone Number: <input name="yourPhone" size="50" type="text"><br />
Email Address: <input name="yourEmail" size="50" type="text"></p>
</p>
<hr />
<br><br><br>
<div align="center">
<input type="button" id="submit" value="Submit Order" onClick="doSubmit()">
<input type="button" id="reset" value="Clear Values" onClick="doClear()">
</div>
<br />
</div></div>
</form>
</body>
</html>
The CSS page is so far:
body
{
color:black;
}
p
{
color:black;
font-size:12px;
font-family: Constantia, Aldhabi, Book Antiqua;
}
h1
{
color:blue;
font-weight:bold;
font-family:"Book Antiqua";
}
h4
{
color:blue;
font-weight:bold;
font-family:"Book Antiqua", Arial;
}
.gallery
{
float:right;
}
div.gallery.hover
{
border: 1px solid orange;
}
div.gallery.img
{
width:110px;
height: 110px;
}
#TotalSystemPrice
{
}
#container
{
display: table;
table-layout: fixed;
width:90%;
height:100%;
border: 1px solid black;
padding: 3px;
}
#left, #right
{
display: table-cell;
}
#left
{
width: 50%;
height: 100%;
background: white;
border: 1px solid blue;
margin:3px 2px;
}
#right
{
width: 50%;
height: 100%;
background-color:ivory;
border: 1px solid blue;
margin: 3px 2px;
}
#computerOrders
{
width:50%;
height:100%;
background-color:white;
}
#orderInfo
{
width:50%;
height:100%;
background-color:white;
}
I want to work my progress bar to certain percentage on each click. Now its is working only up to 75%. On saving it should show 100% but it doesn't showing that.
Similarly by clicking back button it is going upto 25% on it should reset to 0% on clicking back button third time.
HTML
<div id="myProgressbar" class="progress" style="height: 2px;">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%; height: 10px;">
<span class="sr-only">0% Complete</span>
</div>
</div>
<div class="btns">
<button type="button" name="sub" id="back" class="btn btn-default btn-lg" onclick="myFunctions()">back</button>
<button type="button" name="add" id="continue" class="btn btn-success btn-lg" onclick="myFunction()" >Continue</button>
</div>
<form action="/action_page.php" id="person" class="form-inline">
<div class="form-group">
<label for="fname">First Name:<input type="text" class="form-control" id="fname" placeholder="First Name" required="" title="First Name"></label>
</div>
<div class="form-group">
<label for="mname">Middle Name:<input type="text" class="form-control" id="mname" placeholder="Middle Name" title="Middle Name"></label>
</div>
<div class="form-group">
<label for="lname">Last name:<input type="text" class="form-control" id="lname" placeholder="Last Name" title="Last Name"></label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="/action_page.php" id="details" class="form-inline">
<div class="form-group">
<label for="address">Address:<input type="text" class="form-control" rows="5" id="address" placeholder="Enter Address" title="Address"></label>
</div>
<div class="form-group">
<label for="city">City:<input type="text" class="form-control" id="city" placeholder="Enter City"></label>
</div>
<div class="form-group">
<label for="pin">Pin Code:<input type="text" class="form-control" id="pin" placeholder="Enter Pincode"></label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="/action_page.php" id="account" class="form-inline">
<div class="form-group">
<label for="pis">PIS:<input type="text" class="form-control" id="pis" placeholder="PIS"></label>
</div>
<div class="form-group">
<label for="psp">PSP:<input type="text" class="form-control" id="psp" placeholder="PSP"></label>
</div>
<div class="form-group">
<label for="ped">PED:<input type="text" class="form-control" id="ped" placeholder="PED"></label>
</div>
<div class="form-group">
<label for="pno">PNO:<input type="text" class="form-control" id="pno" placeholder="PNO"></label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="/action_page.php" id="premium" class="form-inline">
<div class="form-group">
<label for="pis">IPU:<input type="text" class="form-control" id="pis" placeholder="PIS"></label>
</div>
<div class="form-group">
<label for="psp">NCB:<input type="text" class="form-control" id="psp" placeholder="PSP"></label>
</div>
<div class="form-group">
<label for="ped">TP REF:<input type="text" class="form-control" id="ped" placeholder="PED"></label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<div class="btns">
<button type="button" name="sub" id="back" class="btn btn-default btn-lg" onclick="myFunctions()">back</button>
<button type="button" name="add" id="continue" class="btn btn-success btn-lg" onclick="myFunction()" >Continue</button>
</div>
Javascript
<script>
var num = 1;
document.getElementById("back").disabled = true;
document.getElementById("details").style.display="none";
document.getElementById("person").style.display="block";
document.getElementById("account").style.display="none";
document.getElementById("premium").style.display="none";
function myFunction() {
var listArry = document.getElementsByClassName('list');
for(var i = 0; i < listArry.length; i++){
listArry[i].style.color = "#CCC";
}
if (num==1){
document.getElementById('navlnk1').style.color = "black";
document.getElementById('navlnk').style.color = "#CCC";
document.getElementById("back").disabled = false;
document.getElementById("person").style.display="none";
document.getElementById("details").style.display="block";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 25) {
clearInterval(id);
} else {
width++;
document.getElementById("myProgressbar").style.backgroundColor = "#0FA561";
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=2;
}
else if(num==2){
document.getElementById('navlnk2').style.color = "black";
document.getElementById("details").style.display="none";
document.getElementById("account").style.display="block";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 50) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=3;
}
else if(num==3){
document.getElementById('navlnk3').style.color = "black";
document.getElementById("account").style.display="none";
document.getElementById("premium").style.display="block";
document.getElementById('continue').innerHTML = "Save";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 75) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
}
}
</script>
<script>
var num = 1;
function myFunctions() {
var listArry = document.getElementsByClassName('list');
for(var i = listArry.length; i >0; i--){
}
if (num==3){
document.getElementById('navlnk2').style.color = "black";
document.getElementById('navlnk3').style.color = "#CCC";
document.getElementById('navlnk1').style.color = "#CCC";
document.getElementById('navlnk').style.color = "#CCC";
document.getElementById("premium").style.display="none";
document.getElementById("account").style.display="block";
document.getElementById('continue').innerHTML = "Continue";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 50) {
clearInterval(id);
} else {
width++;
document.getElementById("myProgressbar").style.backgroundColor = "#0FA561";
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=2;
}
else if (num==2){
document.getElementById('navlnk1').style.color = "black";
document.getElementById('navlnk').style.color = "#CCC";
document.getElementById('navlnk2').style.color = "#CCC";
document.getElementById("account").style.display="none";
document.getElementById("details").style.display="block";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 25) {
clearInterval(id);
} else {
width++;
document.getElementById("myProgressbar").style.backgroundColor = "#0FA561";
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=1;
}
else if(num==1){
document.getElementById('navlnk').style.color = "black";
document.getElementById('navlnk1').style.color = "#CCC";
document.getElementById("details").style.display="none";
document.getElementById("person").style.display="block";
document.getElementById("back").disabled = true;
}
}
</script>
<script>
var num = 1;
function myFunctions() {
var listArry = document.getElementsByClassName('list');
for(var i = listArry.length; i >0; i--){
}
if (num==3){
document.getElementById('navlnk2').style.color = "black";
document.getElementById('navlnk3').style.color = "#CCC";
document.getElementById('navlnk1').style.color = "#CCC";
document.getElementById('navlnk').style.color = "#CCC";
document.getElementById("premium").style.display="none";
document.getElementById("account").style.display="block";
document.getElementById('continue').innerHTML = "Continue";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 50) {
clearInterval(id);
} else {
width++;
document.getElementById("myProgressbar").style.backgroundColor = "#0FA561";
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=2;
}
else if (num==2){
document.getElementById('navlnk1').style.color = "black";
document.getElementById('navlnk').style.color = "#CCC";
document.getElementById('navlnk2').style.color = "#CCC";
document.getElementById("account").style.display="none";
document.getElementById("details").style.display="block";
var elem = document.getElementById("myProgressbar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 25) {
clearInterval(id);
} else {
width++;
document.getElementById("myProgressbar").style.backgroundColor = "#0FA561";
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
num=1;
}
else if(num==1){
document.getElementById('navlnk').style.color = "black";
document.getElementById('navlnk1').style.color = "#CCC";
document.getElementById("details").style.display="none";
document.getElementById("person").style.display="block";
document.getElementById("back").disabled = true;
}
}
</script>
Hi i have tried workaround for your requirement... Please try it and let us know.
var width = 40;
function move(data) {
var elem = document.getElementById("myBar");
if(data == 'back' && width != 0){
width = width-10;
elem.style.width = width + '%';
}else if(data == 'continue' && width != 100){
width = width+10;
elem.style.width = width + '%';
}
}
<!DOCTYPE html>
<html>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 40%;
height: 30px;
background-color: #4CAF50;
}
</style>
<body>
<h1>JavaScript Progress Bar</h1>
<div id="myProgress">
<div id="myBar"></div>
</div>
<br>
<button onclick="move('back')">Back</button>
<button onclick="move('continue')">Continue</button>
</body>
</html>
For some reason my javascript stops working after I have submitted a POST request.
Here is what is happening. I load my webpage, fill out the form and click 'Click me' :
Next I click ok in the alert popup and the expected result appears:
I fill out the form, but when I try to click the button nothing happens!
Not even my alert popup.
Here are the files I am using.
My CSS, simple2.css :
body, html {
margin:0;
padding;
height:100%
}
a {
font-size:1.25em;
}
#content {
padding:25px;
}
#fade {
display: none;
position:absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: #ababab;
z-index: 1001;
-moz-opacity: 0.8;
opacity: .70;
filter: alpha(opacity=80);
}
#modal {
display: none;
position: absolute;
top: 45%;
left: 45%;
width: 64px;
height: 64px;
padding:30px 15px 0px;
border: 3px solid #ababab;
box-shadow:1px 1px 10px #ababab;
border-radius:20px;
background-color: white;
z-index: 1002;
text-align:center;
overflow: auto;
}
#results {
font-size:1.25em;
color:red
}
My HTML, simple2.html :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="simple2.css">
<title>simple II</title>
</head>
<body>
<div id="fade"></div>
<div id="modal"> <img id="loader" src="images/loading.gif" /> </div>
<div id="results"><!-- Results are displayed here -->
<form method="post" name="start" target="_blank">
<p>Enter thing1: <input type="text" id="thing1" name="thing1" size="10" /></p>
<p>Enter thing2: <input type="text" id="thing2" name="thing2" size="10" /></p>
<p>Enter thing3: <input type="text" id="thing3" name="thing3" size="10" /></p>
<p>Check thing4: <input type="checkbox" id="thing4" name="thing4" value=1>
<input type="hidden" id="state" name="state" value="one" /></p>
</form>
<button id='clickme' name='clickme'>Click me</button>
<script src="simple2.js?0000000000015"></script>
</div>
</body>
</html>
My javascript, simple2.js :
function openModal() {
document.getElementById('modal').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
function closeModal() {
document.getElementById('modal').style.display = 'none';
document.getElementById('fade').style.display = 'none';
}
function loadAjax(url,data, app, epoch, state) {
console.log ("loadAjax urls is [" + url + "] data is [" + data + "]" );
// document.getElementById('results').innerHTML = '';
console.log ("line 14");
openModal();
console.log ("line 16");
var xhr = false;
console.log ("line 18");
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
closeModal();
console.log ("line 28");
document.getElementById("results").innerHTML = xhr.responseText;
}
}
console.log ("line 32");
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
console.log ("line 35");
}
}
document.querySelector("#results button").addEventListener("click", function(e) {
e.preventDefault();
var inputs = document.querySelectorAll("input");
var params = inputs[0].name + "=" + inputs[0].value;
for( var i = 1; i < inputs.length; i++ ) {
var input = inputs[i];
var name = input.name;
var value = input.value;
params += "&" + name + "=" + value;
}
alert( params );
loadAjax( "/cgi-bin/simple2.py", encodeURI(params));
});
... and finally my cgi script, simple2.py :
#!/usr/bin/env python
import cgi
import os
#import cgitb
import cgitb; cgitb.enable() # for troubleshooting
import time
import calendar
def goto_state_two( a, b, c, d ):
print """
Thank you!<br>
<li>thing1 is [%s]
<li>thing2 is [%s]
<li>thing3 is [%s]
<li>thing4 is [%s]
<hr>
<form method="post" name="start" target="_blank">
<p>Enter thing5: <input type="text" id="thing5" name="thing5" size="10" /></p>
<p>Enter thing6: <input type="text" id="thing6" name="thing6" size="10" /></p>
<p>Enter thing7: <input type="text" id="thing7" name="thing7" size="10" /></p>
<p>Check thing8: <input type="checkbox" id="thing8" name="thing8" value=1>
<input type="hidden" id="state" name="state" value="two" /></p>
</form>
<button id='clickme' name='clickme'>Click me</button>
<script src="simple2.js?%d"></script>
""" % (a,b,c,d,calendar.timegm(time.gmtime()))
def goto_done( a, b, c, d ):
print """
Thank you!<br>
<li>thing1 is [%s]
<li>thing2 is [%s]
<li>thing3 is [%s]
<li>thing4 is [%s]
<hr>
<form method="post" name="start" target="_blank">
<input type="hidden" id="state" name="state" value="done" /></p>
</form>
<button id='clickme' name='clickme'>Click me</button>
<script src="simple2.js?%d"></script>
""" % (a,b,c,d,calendar.timegm(time.gmtime()))
form = cgi.FieldStorage()
state = form.getvalue("state")
if state == 'one' :
thing1 = form.getvalue("thing1", "")
thing2 = form.getvalue("thing2", "")
thing3 = form.getvalue("thing3", "")
thing4 = form.getvalue("thing4", "")
goto_state_two( thing1, thing2, thing3, thing4 )
elif state == 'two' :
thing5 = form.getvalue("thing5", "")
thing6 = form.getvalue("thing6", "")
thing7 = form.getvalue("thing7", "")
thing8 = form.getvalue("thing8", "")
goto_done( thing5, thing6, thing7, thing8 )
elif state == 'done' :
print """
Hurray you did it!<br>
"""
else:
print """
unknown state [%s]
<hr>
""" % ( state )
document.getElementById("results").addEventListener("click", function(e) {
if(e.target && e.target.nodeName == "BUTTON") {
// Move Prevent Default into condition to allow
// other events to bubble.
e.preventDefault();
// This is a Button click we have captured
var inputs = document.querySelectorAll("input");
var params = inputs[0].name + "=" + inputs[0].value;
for( var i = 1; i < inputs.length; i++ ) {
var input = inputs[i];
var name = input.name;
var value = input.value;
params += "&" + name + "=" + value;
}
alert( params );
loadAjax( "/cgi-bin/simple2.py", encodeURI(params));
}
});
I'm trying to show an error message in the span tags using jQuery. I can get the form fields to highlight in a red box and green box if input right but the text wont show up. I'm new to coding and been looking on the web for ideas and fixes, I know I'm missing something and it maybe simple but I'm racking my brains on it.
$(document).ready(function() {
// Name can't be blank
$('#name').on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// Email must be an email
$('#email').on('input', function() {
var input = $(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// Message can't be blank
$('#message').keyup(function(event) {
var input = $(this);
var message = $(this).val();
console.log(message);
if (message) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// After Form Submitted Validation
$("#contact_submit button").click(function(event) {
var form_data = $("#contact").serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $("#contact_submit" + form_data[input]['name'], ['email'], ['message']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {
error_element.removeClass("error").addClass("error_show");
error_free = false;
}
else {
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free) {
event.preventDefault();
}
else {
alert('No errors: Form will be submitted');
}
});
});
.error {
display: none;
margin-left: 10px;
}
.error_show {
color: red;
margin-left: 10px;
}
input.invalid,
textarea.invalid {
border: 2px solid red;
}
input.valid,
textarea.valid {
border: 2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section class="body">
<form id="contact" method="post" enctype="multipart/form-data" action="">
<h1 class="title">Contact</h1>
<div>
<label for="name">Your Fullname</label>
<input type="text" id="name" name="name" required placeholder="Your Name">
<span class="error error_show">This field is required</span>
</div>
<div>
<label for="email">Your Full Email</label>
<input name="email" type="email" id="email" required placeholder="Your Email">
<span class="error error_show">This field is required</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="20" rows="5" required placeholder="Message"></textarea>
<span class="error error_show">This field is required</span>
</div>
<div id="contact_submit">
<button type="submit"></button>
</div>
</form>
</section>
I think you might have made it more complicated than it needed to be. See if the below snippet doesn't work the way you expected.
$(document).ready(function() {
$('#name').on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$('#email').on('input', function() {
var input = $(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$('#message').keyup(function(event) {
var input = $(this);
var message = $(this).val();
console.log(message);
if (message) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$("#contact_submit #submit_button").click(function(event) {
$("#name_error").hide();
$("#email_error").hide();
$("#message_error").hide();
var success = true;
if (!$("#name").hasClass("valid")) {
success = false;
$("#name_error").show();
}
if (!$("#email").hasClass("valid")) {
success = false;
$("#email_error").show();
}
if (!$("#message").hasClass("valid")) {
success = false;
$("#message_error").show();
}
if (success === false) {
event.preventDefault();
}
else {
alert('No errors: Form will be submitted');
}
});
});
.error {
display: none;
margin-left: 10px;
}
.error_show {
color: red;
margin-left: 10px;
display: none;
}
input.invalid,
textarea.invalid {
border: 2px solid red;
}
input.valid,
textarea.valid {
border: 2px solid green;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<section class="body">
<form id="contact" method="post" enctype="multipart/form-data" action="">
<h1 class="title">Contact</h1>
<div>
<label for="name">Your Fullname</label>
<input type="text" id="name" name="name" required placeholder="Your Name">
<span id="name_error" class="error_show">This field is required</span>
</div>
<div>
<label for="email">Your Full Email</label>
<input name="email" type="email" id="email" required placeholder="Your Email">
<span id="email_error" class="error_show">This field is required</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="20" rows="5" required placeholder="Message"></textarea>
<span id="message_error" class="error_show">This field is required</span>
</div>
<div id="contact_submit">
<input type="submit" id="submit_button" value="Submit">
</div>
</form>
</section>
</body>
</html>
var element = $("#contact_submit" + form_data[input]['name'], ['email'], ['message']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
I think these lines don't select the right span.
I got to it on logging the error_element:
console.log(error_element);
Here is a JSFIDDLE with a "working" selector.
var error_element=$("#contact div span");
Now you can change the selector that it fits your needs!