event handler, broken page - javascript

The page should output and execute a temperature converter...
However,
While I'm wanting to test my program, I keep running into this a blank page type error...
can someone kind of proof read this, because I don't know what I'm missing.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var convertTemp = function(){
var f;
var c;
if($("to_Celsius").checked){
f = parseFloat($("degrees_entered").value);
if(isNaN(f)){
alert("please type in a value ");
}
else{
c = (f-32) * 5/9;
$("degrees_computed").value = c.toFixed(0);
}
}
else{
c = parseFloat($("degrees_entered").value);
if(isNaN(c)){
alert("you must enter a valid number for degrees.");
}
else{
f = c * 9/5 + 32;
$("degrees_computed").value = f.toFixed(0);
}
}
};
var toFahrenheit = function(){
$("degree_label_1").firstChild.nodeValue = "Enter C degrees:";
$("degree_label_2").firstChild.nodeValue = "Degrees F";
clearTextBoxes();
$("degrees_entered").focus();
};
var toCelsius = function(){
$("degree_label_1").firstChild.nodeValue = "Enter F degrees: ";
$("degree_label_2").firstChild.nodeValue = "Degrees C: ";
clearTextBoxes();
$("degrees_entered").focus();
};
var clearTextBoxes = function(){
$("degrees_entered").value = "";
$("degrees_computed").value = "";
};
window.onload = function(){
$("convert").onclick = convertTemp;
$("to_Celsius").onclick != toCelsius;
$("to_Fahrenheit").onclick = toFahrenheit;
$("degrees_entered").focus();
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: .5em;
}
#convert {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Convert Temperatures</title>
<link rel="stylesheet" href="styles.css">
<script src="convert_temp.js"></script>
</head>
<body>
<main>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" ><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
</body>
</html>

toCelcius != toCelsius ?
Is that it? A silly typo? The rest looks fine... also watch casing. In your JS you have to_Celsius... but in the html... to_celcius... bad habit for sure

Some issues I verified:
in the line if($("to_Celsius").checked){ you refer to to_Celsius id, but it should be to_celsius (lowercase);
in the lines:
$("to_Celsius").onclick = toCelsius;
$("to_Fahrenheit").onclick = toFahrenheit;
Same thing. Replace both the id with to_celsius and to_fahrenheit.
in this line var toCelcius = function(){, the function is named toCelcius. Just rename it to toCelsius (with s).
Working code: https://jsfiddle.net/mrlew/p8w111ms/

Related

How to get input value after it has been changed by jQuery

I have to get the value of .qty input field but I have a problem that another jQuery function is rewriting the entered value after it gets entered.
For instance, if I enter 1, it gets rounded to 3,3360 but multiplied by 1 so I only can get the written value but I need the value that is changed after (3,3360) and the result should be 33.36 not 10.00:
function myFunctionupdateqtyinput() {
var x = document.getElementById("quantity_60269d6f09cd1");
var a = 3.336;
var b = x.value;
var d = b - (b % a) + a;
var f = d.toPrecision(5);
x.value = f;
}
if ($(".kpt-product-count").length) {
function checkForCount() {
var single_count = parseFloat($(".kpt-product-count").data('kptcount'));
var qty = parseFloat($(".qty").val());
var total = (qty * single_count);
total = total.toFixed(2);
if (isNaN(total)) {
total = single_count.toFixed(2);
}
$(".kpt-product-count-text").find('span').html(total);
}
$(".qty").on('input', checkForCount);
}
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-layout.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-smallscreen.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce.css");
.quantity .qty {
height: 34px;
}
.quantitym2 .qty {
width: 90;
margin-right: 10;
}
.kpt-product-count {
display: inline-flex;
font-size: 15px;
margin-top: 15px;
}
.kpt-product-count-label {
font-weight: 600;
padding-right: 10px;
}
.quantitym2 input::-webkit-inner-spin-button {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity quantitym2">
<label class="screen-reader-text" for="quantity_60269d6f09cd1">Boost quantity</label>
<input type="number" onchange="myFunctionupdateqtyinput()" id="quantity_60269d6f09cd1" class="input-text qty text" value="3.336" step="0.0001" min="0.0001" max="" name="quantity" title="title" size="4" placeholder="" inputmode="">
</div>
<div class="kpt-product-count" data-kptcount="10">
<div class='kpt-product-count-label'>In total: </div>
<div class='kpt-product-count-text'> <span>10</span> </div>
</div>
You need to call the function myFunctionupdateqtyinput()inside the checkForCount function
function checkForCount() {
myFunctionupdateqtyinput();
function myFunctionupdateqtyinput() {
var x = document.getElementById("quantity_60269d6f09cd1");
var a = 3.336;
var b = x.value;
var d = b - (b % a) + a;
var f = d.toPrecision(5);
x.value = f;
}
if ($(".kpt-product-count").length) {
function checkForCount() {
myFunctionupdateqtyinput();
var single_count = parseFloat($(".kpt-product-count").data('kptcount'));
var qty = parseFloat($(".qty").val());
var total = (qty * single_count);
total = total.toFixed(2);
if (isNaN(total)) {
total = single_count.toFixed(2);
}
$(".kpt-product-count-text").find('span').html(total);
}
$(".qty").on('input', checkForCount);
}
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-layout.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-smallscreen.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce.css");
.quantity .qty {
height: 34px;
}
.quantitym2 .qty {
width: 90;
margin-right: 10;
}
.kpt-product-count {
display: inline-flex;
font-size: 15px;
margin-top: 15px;
}
.kpt-product-count-label {
font-weight: 600;
padding-right: 10px;
}
.quantitym2 input::-webkit-inner-spin-button {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity quantitym2">
<label class="screen-reader-text" for="quantity_60269d6f09cd1">Boost quantity</label>
<input type="number" onchange="myFunctionupdateqtyinput()" id="quantity_60269d6f09cd1" class="input-text qty text" value="3.336" step="0.0001" min="0.0001" max="" name="quantity" title="title" size="4" placeholder="" inputmode="">
</div>
<div class="kpt-product-count" data-kptcount="10">
<div class='kpt-product-count-label'>In total: </div>
<div class='kpt-product-count-text'> <span>10</span> </div>
</div>

Captcha Code in JavaScript is not working

I have a validation Form using Javascript. It must validate the name, email and captcha. But through my validation function, the name and email are validated but the captcha is not validated after the onclick of the submit button.
The following functions shows my code:
<script type="text/javascript">
function validateform(){
var cm_name=document.supportus_form.cm_name.value;
var cm_email=document.supportus_form.cm_email.value;
var atpos = cm_email.indexOf("#");
var dotpos = cm_email.lastIndexOf(".");
if (cm_name==null || cm_name=="")
{
alert("Name can't be blank");
return false;
}
else if(atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
var why = "";
if(theform.CaptchaInput.value == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(theform.CaptchaInput.value != ""){
if(ValidCaptcha(theform.CaptchaInput.value) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;
// Validate input against the generated number
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('CaptchaInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
} </script>
The following is my html code for the form which i am using:
<form class="form-horizontal" role="form" action='<?php echo
site_url(); ?>/Welcome/insert_support_info' method="post" enctype="multipart/form-data" onsubmit="return validateform()" name="supportus_form">
<br style="clear:both"/>
<h3 style="margin-bottom: 25px; text-align: center;"><u>Let us Know your Interest</u></h3>
<div class="form-group">
<input type="text" class="form-control" name="cm_name" id="fullname" placeholder="Enter Your Name"/>
<input type="text" class="form-control" name="cm_email" id="email" placeholder="Enter Your E-Mail"/>
<input type="text" class="form-control" name="cm_phone" id="phone" placeholder="Enter Your Phone Number or Mobile Number"/>
<textarea class="form-control" name="cm_message" id="message" rows="3" placeholder="Add your Query"></textarea>
<span class="help-block"><p id="characterLeft" class="help-block ">Limit - 100 words</p></span>
<input class="form-control" name="datetime" value="<?php
date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y h:i:s a', time()); echo $date;
?>" type="hidden" />
<!-- START CAPTCHA -->
<br>
<div class="capbox">
<div id="CaptchaDiv"></div>
<div class="capbox-inner">
Type the above number:<br>
<input type="hidden" id="txtCaptcha">
<input type="text" name="CaptchaInput" id="CaptchaInput" size="15"><br>
</div>
</div>
<br><br>
<!-- END CAPTCHA -->
<button type="submit" class="btn btn-success">Submit</button>
</div>
<hr/>
</form>
I have kept the css to show up the captcha form
<style>
.capbox {
background-color: #92D433;
border: #B3E272 0px solid;
border-width: 0px 12px 0px 0px;
display: inline-block;
*display: inline; zoom: 1; /* FOR IE7-8 */
padding: 8px 40px 8px 8px;
}
.capbox-inner {
font: bold 11px arial, sans-serif;
color: #000000;
background-color: #DBF3BA;
margin: 5px auto 0px auto;
padding: 3px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
#CaptchaDiv {
font: bold 17px verdana, arial, sans-serif;
font-style: italic;
color: #000000;
background-color: #FFFFFF;
padding: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
#CaptchaInput { margin: 1px 0px 1px 0px; width: 135px; }
</style>
With the Above code, the captcha is not working. I am using captcha for the first time.
Hey You are using conditional tags in improper way . That leads to unknown bugs. Following Javascript code works you correct.
function validateform(){
var cm_name=document.supportus_form.cm_name.value;
var cm_email=document.supportus_form.cm_email.value;
var atpos = cm_email.indexOf("#");
var dotpos = cm_email.lastIndexOf(".");
var captha = document.getElementById("txtCaptcha").value;
var capthaValue = document.getElementById('CaptchaInput').value.replace(/ /g,'');
console.log(typeof captha);
if(capthaValue == "" || captha != capthaValue) {
validCaptcha()
}
if (cm_name==null || cm_name=="")
{
alert("Name can't be blank");
return false;
}
else if(atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
function validCaptcha() {
var why = "";
if(capthaValue == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(capthaValue != ""){
if((captha != capthaValue) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;

How to make explanations in quiz disappear when clicked on another answer?

I have been struggling for a while with this since I'm not a pro.
The issue: A quiz. After you click answer A and then submit, you will get an
explanation next to answer A. When you then click answer B and then submit you
will get an explanation next to answer B but explanation A about answer A remains.
This has to disappear.
Here is the link: https://plnkr.co/edit/OvcwBzfFte4A0F0NbNSi?p=preview
<style>
.quizbox {
width: 58%;
max-width: 950px;
border: 1px gray solid;
margin: auto;
padding: 10px;
border-radius: 10px;
border-width: 5px;
border-color: #00A7AE;
margin-top: 7%;
text-align: center;
position: relative;
background: #73B7DB;
}
.row {
text-align: left;
color: white;
margin-left: 10%;
}
span#demo, #demo2, #demo3 {
display: inline;
color: green;
margin-right: 30%;
float:right;
width:50%;
}
</style>
<div class="quizbox">
<!-- open main div -->
<h1>Quiz</h1>
<form id="form1" action=" ">
<div class="row"> <h3>Moths are a member of what order?</h3></div>
<div class="row">
<input name="variable" type="radio" value="0" />Octagon <span id="demo"></span></div>
<div> </div>
<div class="row">
<input name="variable" type="radio" value="0" />Leprosy <span id="demo2"></span></div>
<div class="row">
<input name="variable" type="radio" value="33" />Lepidoptera <span id="demo3"></span></div>
<p> <input type="submit" onclick="myFunction()" value="Submit" /> </p>
</form>Your grade is: <span id="grade">__</span>
<p id="grade2"></p>
</div>
<!-- close quizbox div -->
<span>fdf</span> <span>fdf</span><span>fdf</span>
fd
<script>
document.getElementById("form1").onsubmit = function(e) {
e.preventDefault();
variable = parseInt(document.querySelector('input[name = "variable"]:checked').value);
sub = parseInt(document.querySelector('input[name = "sub"]:checked').value);
con = parseInt(document.querySelector('input[name = "con"]:checked').value);
result = variable + sub + con;
document.getElementById("grade").innerHTML = result;
var result2 = "";
if (result == 0) {
result2 = "I don't think you studied."
};
if (result == 33) {
result2 = "You need to spend more time. Try again."
};
if (result == 66) {
result2 = "I think you could do better. Try again."
};
if (result == 99) {
result2 = "Excellent!"
};
document.getElementById("grade2").innerHTML = result2;
return false; // required to not refresh the page; just leave this here
} //this ends the submit function
function myFunction() {
var checked = document.querySelector("input[name = 'variable']:checked");
var value = checked.parentNode.lastChild.id;
var answer;
switch (value) {
case 'demo':
answer = "An octagon is an object with 8 sides to it";
break;
case 'demo2':
answer = "Leprosy is a chronic infection";
break;
case 'demo3':
answer = "Yes ! this is correct";
break;
}
checked.parentNode.lastChild.innerHTML = answer;
}
</script>
hgf
<div> </div>
You can give each explanation span a class name of "explanation" and clear their texts each time you call myFunction().
Here's a working demo https://plnkr.co/edit/9TIwKXIxP8A01DeKVWuG?p=preview
<style>
.quizbox {
width: 58%;
max-width: 950px;
border: 1px gray solid;
margin: auto;
padding: 10px;
border-radius: 10px;
border-width: 5px;
border-color: #00A7AE;
margin-top: 7%;
text-align: center;
position: relative;
background: #73B7DB;
}
.row {
text-align: left;
color: white;
margin-left: 10%;
}
span#demo, #demo2, #demo3 {
display: inline;
color: green;
margin-right: 30%;
float:right;
width:50%;
}
</style>
<div class="quizbox">
<!-- open main div -->
<h1>Quiz</h1>
<form id="form1" action=" ">
<div class="row"> <h3>Moths are a member of what order?</h3></div>
<div class="row">
<input name="variable" type="radio" value="0" />Octagon <span class="explanation" id="demo"></span></div>
<div> </div>
<div class="row">
<input name="variable" type="radio" value="0" />Leprosy <span class="explanation" id="demo2"></span></div>
<div class="row">
<input name="variable" type="radio" value="33" />Lepidoptera <span class="explanation" id="demo3"></span></div>
<p> <input type="submit" onclick="myFunction()" value="Submit" /> </p>
</form>Your grade is: <span id="grade">__</span>
<p id="grade2"></p>
</div>
<!-- close quizbox div -->
<span>fdf</span> <span>fdf</span><span>fdf</span>
fd
<script>
document.getElementById("form1").onsubmit = function(e) {
e.preventDefault();
variable = parseInt(document.querySelector('input[name = "variable"]:checked').value);
sub = parseInt(document.querySelector('input[name = "sub"]:checked').value);
con = parseInt(document.querySelector('input[name = "con"]:checked').value);
result = variable + sub + con;
document.getElementById("grade").innerHTML = result;
var result2 = "";
if (result == 0) {
result2 = "I don't think you studied."
};
if (result == 33) {
result2 = "You need to spend more time. Try again."
};
if (result == 66) {
result2 = "I think you could do better. Try again."
};
if (result == 99) {
result2 = "Excellent!"
};
document.getElementById("grade2").innerHTML = result2;
return false; // required to not refresh the page; just leave this here
} //this ends the submit function
function myFunction() {
var explanations = document.querySelectorAll(".explanation");
for(var x = 0; x < explanations.length; x++) {
explanations[x].innerHTML = "";
}
var checked = document.querySelector("input[name = 'variable']:checked");
var value = checked.parentNode.lastChild.id;
var answer;
switch (value) {
case 'demo':
answer = "An octagon is an object with 8 sides to it";
break;
case 'demo2':
answer = "Leprosy is a chronic infection";
break;
case 'demo3':
answer = "Yes ! this is correct";
break;
}
checked.parentNode.lastChild.innerHTML = answer;
}
</script>
hgf
<div> </div>
In html, add class to all <input name="variable"> (note that you cannot have duplicating name attribute on multiple input):
<input class="variable" ...>
Add lines in your myFunction() to get inputs that is not checked:
function myFunction() {
var notChecked = document.getElementsByClassName('variable');
var checked = document.querySelector("input[name = 'variable']:checked");
var value = checked.parentNode.lastChild.id;
var answer;
switch (value) {
case 'demo':
answer = "An octagon is an object with 8 sides to it";
break;
case 'demo2':
answer = "Leprosy is a chronic infection";
break;
case 'demo3':
answer = "Yes ! this is correct";
break;
}
for (var i = 0, len = notChecked.length; i < len; i++){
notChecked[i].parentNode.lastChild.innerHTML = '';
}
checked.parentNode.lastChild.innerHTML = answer;
}

Can somebody explains that why my input fields value is not changing

I am making a simple word counter program in JavaScript. I am fairly new in JavaScript world so excuse me if I am asking an rudimentary and simple enough question. I'm getting everything working that the string of text from textarea is splitted into words array and i can log number of words to console but can't display them into a text field where I want them to appear. Hope that someone can help here. Thanks
var btn = document.getElementById("btn");
var numWords = document.getElementById("output");
var str = document.getElementById("txtBox");
btn.onclick = function()
{
var words = str.value.split(" ");
numWords.innerHTML.value = words.length;
console.log( words.length );
};
.container
{
width: 600px;
margin: 0 auto;
}
textarea
{
width: 560px;
padding: 10px;
background-color: #dfdfdf;
color: #333;
font-size: 18px;
}
input
{
text-align: center;
padding: 10px;
margin-top: 15px;
}
input[type="submit"]
{
float: right;
margin-right: 15px;
background-color: #84ac49;
border: 0;
color: #fff;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="container">
<from>
<textarea name="txtBox" id="txtBox" cols="30" rows="10"></textarea><br/>
<input type="text" value = 0 id="output">
<input type="submit" value="Count Words" id="btn">
</from>
</div>
</body>
</html>
move getting value in click function event
btn.onclick = function()
{
var str = document.getElementById("txtBox").value
var words = str.split(" ");
numWords.value = words.length;
console.log( words.length );
};
JSFIDDLE
btn.onclick = function () {
var words = str.value.split(" ");
numWords.value = words.length;
console.log(words.length);
};
also you can set input like this:
<input value="Count Words" id="btn">
when You click on count button You will get word count.
HTML
<textarea id="inputString" cols="50" rows="4"></textarea>
<br>
<input type="button" name="Convert" value="Count Words" onClick="countWords();">
<input id="wordcount" type="text" value="0" size="6">
Javascript
countWords=function(){
s=document.getElementById("inputString").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
document.getElementById("wordcount").value = s.split(' ').length;
}
Here is a demo :https://jsfiddle.net/DhwaniSanghvi/tdn3x72g/

My javascript stops working after ajax response

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));
}
});

Categories