javascript quiz not working as intended - javascript

I've been trying to have this javascript quiz with 5 questions that can display both an image or an onclick button for sound.
The point of the quiz is to guess which artist belong to which picture or sound.
But the problems are when I try to add a picture or button in the box where is says "hvilket band er dette?" it crashes the quiz. Also it doesnt seem to count the amount of points for correct and incorrect answears.
Would be greatful if anyone knew how to fix it.
EDIT: also need help with centering the quiz underneath the "banner".
The code:
<html>
<head>
<meta charset="UTF-8">
<title>fagdag 26.04.2016 helårs</title>
<style>
#banner {
text-align: center;
width: 50%;
}
.pulsate {
-webkit-animation: pulsate 3s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.5;
}
#-webkit-keyframes pulsate {
0% {
opacity: 0.5;
}
50% {
opacity: 1.0;
}
100% {
opacity: 0.5;
}
div#test{
border:#000 1px solid;
padding:10px 40px 40px 40px;
}
}
</style>
</head>
<body>
<div onmouseover="PlaySound('mySound')" onmouseout="StopSound('mySound')" id="banner">
<img src="http://i.imgur.com/SrnpgpD.jpg" style="z-index: 0; position: absolute; text-align; center">
<img class="pulsate" src="http://i.imgur.com/t2Pil1a.png" style="z-index: 1; position: absolute; text-align;center">
</div>
<br>
<br>
<h2 id="test_status"></h2>
<h2> Hvilket band er dette? </h2>
<div id="test"></div>
<audio id='mySound' src='vivalavida.mp3' />
<script type="text/javascript">
function PlaySound(soundobj) {
console.log("hi")
var thissound = document.getElementById(soundobj);
thissound.play();
}
function StopSound(soundobj) {
var thissound = document.getElementById(soundobj);
thissound.pause();
thissound.currentTime = 0;
}
</script>
<script>
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, chD, chE, correct = 0;
var questions = [
[ "Hvilket band er dette?", "Linkin Park", "Green Day", "Coldplay", "Billy Talent", "Hollywoodundead" ,"B" ],
[ "Hvilket band er dette?", "Linkin Park", "Green Day", "Coldplay", "Billy Talent", "Hollywoodundead" ,"A" ],
[ "Hvilket band er dette?", "Linkin Park", "Green Day", "Coldplay", "Billy Talent", "Hollywoodundead" ,"B" ],
[ "Hvilket band er dette?", "Linkin Park", "Green Day", "Coldplay", "Billy Talent", "Hollywoodundead" ,"D" ],
[ "Hvilket band er dette?", "Linkin Park", "Green Day", "Coldplay", "Billy Talent", "Hollywoodundead" ,"E" ],
];
function _(x){
return document.getElementById(x);
}
function renderQuestion(){
test = _("test");
if(pos >= questions.length){
test.innerHTML = "<h2>Du fikk "+correct+" av "+questions.length+" spørsmål riktige</h2>";
_("test_status").innerHTML = "Quiz fullført";
pos = 0;
correct = 0;
return false;
}
_("test_status").innerHTML = "Spørsmål "+(pos+1)+" av "+questions.length;
question = questions[pos][0];
chA = questions[pos][1];
chB = questions[pos][2];
chC = questions[pos][3];
chD = questions[pos][4];
chE = questions[pos][5];
test.innerHTML = "<h3>"+question+"</h3>";
test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br>";
test.innerHTML += "<input type='radio' name='choices' value='D'> "+chD+"<br>";
test.innerHTML += "<input type='radio' name='choices' value='E'> "+chE+"<br><br>";
test.innerHTML += "<button onclick='checkAnswer()'>Neste</button>";
}
function checkAnswer(){
choices = document.getElementsByName("choices");
for(var i=0; i<choices.length; i++){
if(choices[i].checked){
choice = choices[i].value;
}
}
if(choice == questions[pos][5]){
correct++;
}
pos++;
renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
</script>
</body>
</html>

Related

How could I optimize this code? I need to do it in all 50 states, and in each state the text changes

How could I optimize this code? I need to do it in all 50 states, and in each state the text changes so I would like to know if there is another way than adding fifty ifs conditions
What I want to do is add dynamic text in each state which are 50 and in each of them there is different information, this is being developed in wordpress
if there is some other way to make it more optimal or better practice, maybe using jqueryde. thanks
<select onchange="states_info(this.value)" name="country" id="country">
<option value="Alabama" selected><?php echo "Alabama"?></option>
<option value="Alaska"><?php echo "Alaska" ?></option>
<option value="Arizona"><?php echo "Arizona" ?></option>
<option value="Wisconsin"><?php echo "Wisconsin" ?></option>
</select>
<h2 id="Title" ><?php echo "Alabama Requirements"?></h2>
<p id="credits" ><?php echo "Total Credits: 12 "?></p>
<ul>
<li id="li_1" ><?php echo "At least 1 in Ethics"?></li>
<li id="li_2" ><?php echo "At least 6 Live"?></li>
<li id="li_3" class="hide"></li>
</ul>
<p id ="change_due" class="b" ></p>
<p id="Deadline"><?php echo " Deadline: December 31st"?></p>
<p id="change" class="b"></p>
<p id="reported" ><?php echo "How are credits reported?"?></p>
<button id="webinars" class="button-custom"></button>
<button id="ethics" class="button-custom"></button>
<style>
p.b{
font-style: italic;
display:none;
color: blue;
}
.hide{
display:none;
}
.thick {
font-weight: bold;
}
.normal {
font-weight: normal;
}
.button-custom{
background-color: Transparent;
background-repeat:no-repeat;
border-color: #5CCAF3;
color: #5CCAF3;
border-radius:5px;
cursor:pointer;
overflow: hidden;
text-align: center;
width: 100%;
display:none;
height: 45px;
}
</style>
<script>
function states_info(state){
if(state =="Alabama"){
document.getElementById("Title").innerHTML = "Alabama Requirements";
document.getElementById("credits").innerHTML = "Total Credits: 12 credit hours every year";
document.getElementById("li_1").style.display = "block";
var normal = document.getElementById("li_1");
normal.classList.remove('thick');
normal.classList.add("normal");
document.getElementById("li_1").innerHTML = "• At least 1 in Ethics";
document.getElementById("li_2").style.display = "block";
var bold = document.getElementById("li_2");
bold.classList.remove('thick');
bold.classList.add("normal");
document.getElementById("li_2").innerHTML = "• At least 6 Live";
document.getElementById("Deadline").innerHTML = " Deadline: December 31st";
document.getElementById("change").style.display = "none";
document.getElementById("reported").innerHTML = "How are credits reported? Alabama .";
document.getElementById("webinars").style.display = "none";
document.getElementById("ethics").style.display = "none";
document.getElementById("change_due").style.display = "none";
}
if(state == "Wisconsin"){
document.getElementById("Title").innerHTML = "Wisconsin Requirements";
document.getElementById("credits").innerHTML = "Total Credits: 30 credit hours every 2 years.";
document.getElementById("li_1").style.display = "block";
document.getElementById("li_1").innerHTML = "• At least 3 in Ethics ";
document.getElementById("li_2").style.display = "none";
document.getElementById("change_due").style.display = "block";
document.getElementById("change_due").innerHTML = "*Change due";
document.getElementById("Deadline").innerHTML = "Deadline: December 31st";
document.getElementById("change").style.display = "none";
document.getElementById("reported").innerHTML = "How are credits reported? Wisconsin ";
document.getElementById("webinars").style.display = "block";
document.getElementById("webinars").innerHTML = "Live webinars for Wisconsin";
document.getElementById("ethics").style.display = "block";
document.getElementById("ethics").innerHTML = "Live ethics webinars for Wisconsin";
}
}
</script>
Use an object that contains the information about each state:
const state_data = {
Alabama: {
credits: "Total Credits: 12 credit hours every year",
Deadline: "December 31st",
change_due: null,
li_1: "• At least 1 in Ethics",
li_2: "• At least 6 Live",
reported: "How are credits reported? Alabama .",
change: null,
webinars: null,
ethics: null
},
Wisconsin: {
credits: "Total Credits: 30 credit hours every 2 years.",
deadline: "December 31st",
change_due: "*Change due",
li_1: "• At least 3 in Ethics",
li_2: null,
reported: "How are credits reported? Wisconsin .",
change: null,
webinars: "Live webinars for Wisconsin",
ethics: "Live ethics webinars for Wisconsin"
},
...
};
function states_info(state) {
document.getElementById("Title").innerHTML = `${state} Requirements`;
Object.entries(state_data[state]).forEach((id, value) => {
let el = document.getElementById(id);
if (value !== null) {
el.style.display = "block";
el.innerHTML = value;
} else {
el.style.display = "none";
}
});
}

Submit Button Not Changing Questions

I am building a cute webpage for my teacher (who's very fun) as a Christmas present, but whenever I enter text into the input box and submit any question past the first, the code marks it as incorrect. I thought I had fixed this problem when I changed the question submit, every time the question changes, but apparently not. Can someone tell me what I'm doing wrong?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Funn Chunn | Quiz</title>
<link rel="icon" href="images/alabama logo.png"/>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body onload="firstQ();">
<div class='container'>
<div class='row'>
<h1 id='mainHeader'>Funn Chunn | Quiz</h1>
</div>
<div class='row'>
<h3 id='questionBox'></h3>
</div>
<div class='row'>
<form id="inputBoxOuter">
<input id='inputBox' type='text'></br>
<button class='btn btn-lg btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>
</form>
</div>
<div class='row'>
<form id="playAgainOuter">
</form>
</div>
<div class="row">
<p id="subText"></p>
</div>
<div class="row">
<div id="logoImgOuter"><img class="mx-auto" id="logoImg" src="images/alabama logo.png"/></div>
</div>
</div>
<script src="script.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
JavaScript
var mainHeaderJs = document.getElementById("mainHeader");
var questionBoxJs = document.getElementById("questionBox");
var inputBoxJs = document.getElementById("inputBox");
var inputBoxOuterJs = document.getElementById("inputBoxOuter");
var subTextJs = document.getElementById("subText");
var logoImgOuterJs = document.getElementById("logoImgOuter");
var playAgainOuter = document.getElementById("playAgainOuter");
var playerScore = 0;
function finalScore() {
mainHeaderJs.innerHTML = "You Got a Score of " + playerScore + " Out of 10";
playAgainOuter.innerHTML = "<button class='btn btn-lg btn-info mx-auto' id='playAgain' onclick='playAgain();'>Play Again</button>"
questionBoxJs.innerHTML = "";
inputBoxOuterJs.innerHTML = "";
}
function playAgain() {
mainHeaderJs.innerHTML = "Funn Chunn | Quiz";
firstQ();
playerScore = 0;
playAgainOuter.innerHTML = "";
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>";
}
function moveOnGood() {
subTextJs.innerHTML = "Correct! Moving on to the next question";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function moveOnBad() {
subTextJs.innerHTML = "Moving on to the next question...";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function firstQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 1: What is Mrs. Chunn's Favorite Team?";
}, 2000);
}
function firstQAnswer() {
var Q1Answer = inputBoxJs.value;
Q1Answer = Q1Answer.toUpperCase();
if (Q1Answer == "ALABAMA") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON TIDE") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
moveOnBad();
secondQ();
}
}
function secondQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 2: Is Mrs. Chunn a Millenial?";
}, 2000);
}
function secondQAnswer() {
var Q2Answer = inputBoxJs.value;
Q2Answer = Q2Answer.toUpperCase();
if (Q2Answer == "YES") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "YEAH") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "Y") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswerAlt();'>Enter</button>";
moveOnBad();
thirdQ();
}
}
This isn't the best solution, but its one that should work. Just initialize inputBoxjs = ''; and update inputBoxjs at the start of every question function.
So change
var inputBoxJs = document.getElementById("inputBox");
to
var inputBoxJs = '';
and add this line
inputBoxJs = document.getElementById("inputBox");
above your Q1Answer and Q2Answer variables.
Then just add your thirdQ function and variables after you're finished with your Q2 functions.
Hopefully this helps.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Funn Chunn | Quiz</title>
<link rel="icon" href="images/alabama logo.png"/>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body onload="firstQ();">
<div class='container'>
<div class='row'>
<h1 id='mainHeader'>Funn Chunn | Quiz</h1>
</div>
<div class='row'>
<h3 id='questionBox'></h3>
</div>
<div class='row'>
<form id="inputBoxOuter">
<input id='inputBox' type='text'> <br/>
<button class='btn btn-lg btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>
</form>
</div>
<div class='row'>
<form id="playAgainOuter">
</form>
</div>
<div class="row">
<p id="subText"></p>
</div>
<div class="row">
<div id="logoImgOuter"><img class="mx-auto" id="logoImg" src="images/alabama logo.png"/></div>
</div>
</div>
<script src="script.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
<script>
var mainHeaderJs = document.getElementById("mainHeader");
var questionBoxJs = document.getElementById("questionBox");
var inputBoxJs = '';
var inputBoxOuterJs = document.getElementById("inputBoxOuter");
var subTextJs = document.getElementById("subText");
var logoImgOuterJs = document.getElementById("logoImgOuter");
var playAgainOuter = document.getElementById("playAgainOuter");
var playerScore = 0;
function finalScore() {
mainHeaderJs.innerHTML = "You Got a Score of " + playerScore + " Out of 10";
playAgainOuter.innerHTML = "<button class='btn btn-lg btn-info mx-auto' id='playAgain' onclick='playAgain();'>Play Again</button>"
questionBoxJs.innerHTML = "";
inputBoxOuterJs.innerHTML = "";
}
function playAgain() {
mainHeaderJs.innerHTML = "Funn Chunn | Quiz";
firstQ();
playerScore = 0;
playAgainOuter.innerHTML = "";
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='firstQAnswer();'>Enter</button>";
}
function moveOnGood() {
subTextJs.innerHTML = "Correct! Moving on to the next question";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function moveOnBad() {
subTextJs.innerHTML = "Moving on to the next question...";
setTimeout(function () {
subTextJs.innerHTML = "";
}, 2000);
}
function firstQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 1: What is Mrs. Chunn's Favorite Team?";
}, 2000);
}
function firstQAnswer() {
inputBoxJs = document.getElementById("inputBox");
var Q1Answer = inputBoxJs.value;
Q1Answer = Q1Answer.toUpperCase();
if (Q1Answer == "ALABAMA") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else if (Q1Answer == "CRIMSON TIDE") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
secondQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswer();'>Enter</button>";
moveOnBad();
secondQ();
}
}
function secondQ() {
setTimeout(function () {
questionBoxJs.innerHTML = "Question 2: Is Mrs. Chunn a Millenial?";
}, 2000);
}
function secondQAnswer() {
inputBoxJs = document.getElementById("inputBox");
var Q2Answer = inputBoxJs.value;
Q2Answer = Q2Answer.toUpperCase();
if (Q2Answer == "YES") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "YEAH") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else if (Q2Answer == "Y") {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='thirdQAnswer();'>Enter</button>";
playerScore += 1;
moveOnGood();
thirdQ();
} else {
inputBoxOuterJs.innerHTML = "<input id='inputBox' type='text'></br><button class='btn btn-info' id='submitBtn' onclick='secondQAnswerAlt();'>Enter</button>";
moveOnBad();
thirdQ();
}
}
</script>

persistent checkboxes, dynamic table, php javascript

I've been working on this nonstop and none of the online suggestions have worked.
I have a dynamically created table that refreshes every 5 seconds. There are checkboxes on the table, if you check a box it highlights the row. When the page refreshes all checked states are lost, I need them to be saved, either by local storage or a cookie or even writing out to a file.
Please help and thanks in advance.
My currently working code that does not retain the checked state:
<HTML>
<HEAD>
<TITLE>list</TITLE>
<META name="description" content="">
<META name="keywords" content="">
<meta http-equiv="refresh" content="5" >
<style>
.inv {
display: none;
}
table.sortable thead {
background-color:#999;
color:#222222;
font-weight: bold;
cursor: default;
}
table.sortable tbody {
counter-reset: sortabletablescope;
}
table.sortable thead tr::before {
content: "";
display: table-cell;
}
table.sortable tbody tr::before {
content: counter(sortabletablescope);
counter-increment: sortabletablescope;
display: table-cell;
}
</style>
<script src="../../sorttable.js"></script>
<script>
function toggle_highlight(inputTagReference)
{
var is_checked = inputTagReference.checked; //true or false
if(is_checked)
{
inputTagReference.parentNode.parentNode.style.backgroundColor="yellow";
}
else
{
inputTagReference.parentNode.parentNode.style.backgroundColor="";
}
}
</script>
</HEAD>
<BODY BGCOLOR="#dddddd" TEXT="#000000" LINK="#0000FF" VLINK="#800080">
<h1 align="center">List</h1>
<p align="center"> </p>
<p align="center">
<?php
echo '<div>';
//Create file with headers
system("cmd /C makeit.bat");
//Create html table
echo '<p align="center"> </p>';
echo '<p align="center"> </p>';
echo '<table class="sortable" align="center">';
$row = 0;
$handle = fopen("readylist.txt", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 0) {
// this is the first line of the file
// it contains titles of columns
$num = count($data);
echo "<thead>\n<tr>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<th align='left' height='75' width='135'>" . $data[$c] . "</th>";
}
echo "<td></td>";
echo "</tr>\n</thead>\n\n<tbody>";
} else {
// this handles the rest of the lines of the file
$num = count($data);
echo "<tr id=Row0$row>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<td id=Col0$c>" . $data[$c] . "</td>";
}
echo "<td><input type='checkbox' name='Chk$row id=Chk$row' value='Chk$row' onclick='toggle_highlight(this)'></td>";
echo "</tr>\n";
}
}
fclose($handle);
echo "</tbody>\n</table>";
echo '</div>';
?>
</p>
</BODY>
</HTML>
Here it is with nonworking solution:
<HTML>
<HEAD>
<TITLE>list</TITLE>
<META name="description" content="">
<META name="keywords" content="">
<meta http-equiv="refresh" content="5" >
<style>
#checkbox-container{
margin: 10px 5px;
}
#checkbox-container div{
margin-bottom: 5px;
}
#checkbox-container button{
margin-top: 5px;
}
input[type=text] {
padding: .5em .6em;
display: inline-block;
border: 1px solid #ccc;
box-shadow: inset 0 1px 3px #ddd;
border-radius: 4px;
}
.inv {
display: none;
}
table.sortable thead {
background-color:#999;
color:#222222;
font-weight: bold;
cursor: default;
}
table.sortable tbody {
counter-reset: sortabletablescope;
}
table.sortable thead tr::before {
content: "";
display: table-cell;
}
table.sortable tbody tr::before {
content: counter(sortabletablescope);
counter-increment: sortabletablescope;
display: table-cell;
}
</style>
<script src="../../sorttable.js"></script>
<script src="../../jquery.js"></script>
<script>
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var $checkboxes = $("#checkbox-container :checkbox");
var $button = $("#checkbox-container button");
function allChecked(){
return $checkboxes.length === $checkboxes.filter(":checked").length;
}
function updateButtonStatus(){
$button.text(allChecked()? "Uncheck all" : "Check all");
}
function handleButtonClick(){
$checkboxes.prop("checked", allChecked()? false : true)
}
function updateStorage(){
$checkboxes.each(function(){
formValues[this.id] = this.checked;
});
formValues["buttonText"] = $button.text();
localStorage.setItem("formValues", JSON.stringify(formValues));
}
$button.on("click", function() {
handleButtonClick();
updateButtonStatus();
updateStorage();
});
$checkboxes.on("change", function(){
updateButtonStatus();
updateStorage();
});
// On page load
$.each(formValues, function(key, value) {
$("#" + key).prop('checked', value);
});
$button.text(formValues["buttonText"]);
</script>
<script>
function toggle_highlight(inputTagReference)
{
var is_checked = inputTagReference.checked; //true or false
if(is_checked)
{
inputTagReference.parentNode.parentNode.style.backgroundColor="yellow";
}
else
{
inputTagReference.parentNode.parentNode.style.backgroundColor="";
}
}
</script>
</HEAD>
<BODY BGCOLOR="#dddddd" TEXT="#000000" LINK="#0000FF" VLINK="#800080">
<h1 align="center">List</h1>
<p align="center"> </p>
<p align="center">
<?php
echo '<div id="checkbox-container">';
//Create file with headers
system("cmd /C makeit.bat");
//Create html table
echo '<p align="center"> </p>';
echo '<p align="center"> </p>';
echo '<table class="sortable" align="center">';
$row = 0;
$handle = fopen("readylist.txt", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 0) {
// this is the first line of the file
// it contains titles of columns
$num = count($data);
echo "<thead>\n<tr>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<th align='left' height='75' width='135'>" . $data[$c] . "</th>";
}
echo "<td></td>";
echo "</tr>\n</thead>\n\n<tbody>";
} else {
// this handles the rest of the lines of the file
$num = count($data);
echo "<tr id=Row0$row>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<td id=Col0$c>" . $data[$c] . "</td>";
}
echo "<td><input type='checkbox' name='Chk$row id=Chk$row' value='Chk$row' onclick='toggle_highlight(this)'></td>";
echo "</tr>\n";
}
}
fclose($handle);
echo "</tbody>\n</table>";
echo '</div>';
?>
</p>
</BODY>
</HTML>
here is the code from the page that answered the persistent checkbox question, this page works for me, but the code from it on my page does not.
<html >
<head>
<meta charset="UTF-8">
<title>CodePen - A Pen by SitePoint</title>
<style>
#checkbox-container{
margin: 10px 5px;
}
#checkbox-container div{
margin-bottom: 5px;
}
#checkbox-container button{
margin-top: 5px;
}
input[type=text] {
padding: .5em .6em;
display: inline-block;
border: 1px solid #ccc;
box-shadow: inset 0 1px 3px #ddd;
border-radius: 4px;
}
</style>
</head>
<body translate="no" >
<input type="text" placeholder="Type something here" />
<div id="checkbox-container">
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
<button>Check All</button>
</div>
<script src='../../jquery.js'></script>
<script>
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var $checkboxes = $('#checkbox-container :checkbox');
var $button = $('#checkbox-container button');
function allChecked() {
return $checkboxes.length === $checkboxes.filter(':checked').length;
}
function updateButtonStatus() {
$button.text(allChecked() ? 'Uncheck all' : 'Check all');
}
function handleButtonClick() {
$checkboxes.prop('checked', allChecked() ? false : true);
}
function updateStorage() {
$checkboxes.each(function () {
formValues[this.id] = this.checked;
});
formValues['buttonText'] = $button.text();
localStorage.setItem('formValues', JSON.stringify(formValues));
}
$button.on('click', function () {
handleButtonClick();
updateButtonStatus();
updateStorage();
});
$checkboxes.on('change', function () {
updateButtonStatus();
updateStorage();
});
$.each(formValues, function (key, value) {
$('#' + key).prop('checked', value);
});
$button.text(formValues['buttonText']);
//# sourceURL=pen.js
</script>
</body>
</html>
Well, it's been a day, and I don't see anything here.
My assumption is that you guys are finding this just as difficult as I am.
I am still working on this and here is my logic.
I will have to get the insidehtml of one of the cells in the row as part of the onclick event, then set a cookie or use session to store the variable based on the row, and then an onload event that reads that session or cookie and checks the appropriate boxes and highlights the appropriate rows.
If anyone has any comments or suggestions, they are entirely welcome.
tia

Read and write excel using javascript and hta

Here is the code to read the data from the excel sheet and paste that data into html table. It shows an error,when i convert the data from html table to excel sheet,but at the sametime this coding is working in vbscript,not working in javascript what is the solution for that..
<html>
<head>
<HTA:application
Applicationname="MyApp"
BORDER="dialog"
BORDERSTYLE="complex"
Caption="yes"
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SINGLEINSTANCE="no"
SYSMENU="yes"
VERSION="2.0"
WINDOWSTATE="maximize"/>
<title>Read Excel</title>
<style type="text/css">
body
{
background-color:White;
}
P
{
font:bold 18px arial;
}
</style>
<script language="javascript" type="text/javascript">
var rowCount,colCount,selectexcel,objExcel,tempcol,intRow,intCol;
var rowData;
var mySpan;
var textData;
function ReadExcelData()
{
selectexcel = prompt("Please enter the file path", "D:\VBScriptTrainee\Sample.xlsx");
objExcel = new ActiveXObject("Excel.Application");
objExcel.Visible = false;
objExcel.Workbooks.Open(selectexcel);
rowCount=objExcel.ActiveWorkbook.Sheets(1).UsedRange.Rows.Count
colCount=objExcel.ActiveWorkbook.Sheets(1).UsedRange.Columns.Count
alert(rowCount);
alert(colCount);
//colCount=colCount+1;
tempcol=colCount;
rowData="<table border=2>";
for (intRow=1;intRow <= rowCount;intRow++)
{
rowData = rowData + "<tr>";
for (intCol=1;intCol <= colCount;intCol++)
{
if ((intRow != 1) && (intCol ==tempcol))
{
rowData = rowData + "<td>" + "<input type='checkbox' id='flag_id' name='flag' />" + "</td>";
}
else if (intRow ==1)
{
rowData = rowData + "<td>" + objExcel.Cells(intRow,intCol).Value + "</td>";
}
else
{
rowData= rowData + "<td><div contentEditable='True'>" + objExcel.Cells(intRow,intCol).Value + "</div></td>";
}
}
rowData = rowData + "</tr>";
}
rowData =rowData + "</table>";
//document.write(rowData);
mySpan = document.getElementById('Span_id_two');
mySpan.innerHTML = rowData + "<br>";
//objExcel = undefined;
}
function WriteExcelData()
{
//mwresult = Msgbox ("Are you Sure to Write ?",vbOKCancel)
//var objExcelTwo;
//objExcelTwo = new ActiveXObject("Excel.Application");
//objExcelTwo.Visible = true;
//objExcelTwo.Workbooks.Open(selectexcel);
var tableValue;
var mySpan=document.getElementById('Span_id_two');
textData=mySpan.innerHTML;
var tab=document.getElementsByTagName("table")(0);
var mytable = document.getElementsByTagName("table")(0).rows.length;
//document.write(mytable);
var mytable1= document.getElementsByTagName("table")(0).rows(0).cells.length;
//document.write(mytable1);
for(n = 0;n<=(mytable-1);n++)
{
for(j = 0;j<=(mytable1-1);j++)
{
objExcel.Cells(n+1,j+1).Value = tab.Rows(n).Cells(j).innerHTML;
tableValue = tab.Rows(n).Cells(j).innerHTML;
if(tableValue == "<INPUT id=flag_id type=checkbox CHECKED name=flag>")
{
objExcel.Cells(n+1,mytable1).Value="Yes";
}
if(tableValue == "<INPUT id=flag_id type=checkbox name=flag>")
{
objExcel.Cells(n+1,mytable1).Value="No";
}
}
}
//var find ="<*>";
//var rplace =" ";
//objExcel.Cells.Replace find,rplace;
//MsgBox "Data Exported Successfully",vbInformation
//objExcel.ActiveWorkbook.Save;
//Set objExcel=nothing
}
</script>
</head>
<body>
<center>
<img src="Excel.png" height=200 width=300/>
</center>
<center>
<h1 align="center" style="color:blue"><img src="icon-developer-icon.png" height=100px width=100px/>
Read Excel (Row by Row)</h1><br>
<input type="button" name="Read" value="Click To Read" onclick="ReadExcelData()"/>
<input type="button" name="Write" value="Click To Write" onclick="WriteExcelData()"/>
</center>
<br>
<br>
<div>
<center>
<!--<table border="2px" color="Red">
<th id="thead"></th>
<tr>
<td>-->
<br>
<!--<div class="jumbotron">-->
<span ID="Span_id_two" Style="Color:blue;" name="text_name">
</span>
<br>
<!--</td>
</tr>
</table>-->
<marquee direction="Right" style="Color:red;">**Note : Select only excel files**</marquee>
</center>
</div>
</div>
</div>
</div>
</body>
</html>
It shows the following error 'object doesn't support this property or method'
in WriteExcelData function.

Toggle hide/show table td in .hta

I've seen several of posts regarding this subject, but I have not managed to solve my own problem despite of having tried different methods.
I am programming in a .hta file, where I have all my notes titles listed above each other. Whenever you click a note title the description should appear (toggle/expand) under the title. All the notes should start hidden.
sub searchdata
SQL_query = "SELECT * FROM dvd WHERE Title LIKE '%"& txtsrch.value &"%' OR Notes LIKE '%"& txtsrch.value &"%' ORDER BY Title"
Set rsData = conn.Execute(SQL_query)
strHTML2 = strHTML2 & ""
Do Until rsData.EOF = True
strHTML2 = strHTML2 & "<table width='97%' border='0' id='bodytext' style='border-bottom: solid #000000 1px;'><tr><span class'togglelink'><td width='70%' style='cursor: pointer'><b>" & rsData("Title") & "</b></td></span><td align='right' style='color: #000'>" & rsData("Cat") & " <a href='#' onclick='editUser("& rsData("ID") &")' language='vbscript'><img src='images/arrow-blue.png' border='0' title='Rediger notatet' /></a> <a href='#' onclick='deleteUser("& rsData("ID") &")' language='vbscript'><img src='images/slet.png' border='0' title='Slet notatet' /></a></td><tr><span class='toggle' style='display: block'><td colspan='2'>" & rsData("Notes") & "</td></span></tr></table>"
rsData.moveNext ' go to next record
Loop
strHTML2 = strHTML2 & ""
searchIT.innerHTML = strHTML2
end sub
I am using this JS script to run it:
<script type="text/javascript">
$(document).ready(function () {
$('.toggle').hide();
$('span.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).next('.toggle')
$('.toggle').not(elem).hide('fast');
elem.toggle('fast');
});
});
</script>
I can easily get the script to work when testing with just plain text.
JSFiddle
Side question: Is programming in a HTA really so different from HTML? I'm running in to a lot of problems trying to convert my whole site (MySQL, PHP, HTML) to working in HTA.
Thanks in advance!
Update: Listed my whole .hta script:
<html>
<HTA:APPLICATION ID="oHTA"
APPLICATIONNAME="myApp"
BORDER="thick"
CAPTION="yes"
ICON=./images/Icon.ico
MAXIMIZEBUTTON="yes"
MINIMIZEBUTTON="yes"
SHOWINTASKBAR="yes"
SINGLEINSTANCE="no"
SYSMENU="yes"
RESIZE="yes"
VERSION=7.2
WINDOWSTATE="normal"
contextMenu=no
>
<head>
<style>
#vis1{
display:none;
}
</style>
<script type="text/javascript"> // Width and height in pixel to the window
window.resizeTo(683,725);
</script>
<script type="text/javascript">
var enablepersist="on" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious="Yes" //Collapse previously open content when opening present? (yes/no)
if (document.getElementById){
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}
function getElementbyClass(classname){
ccollect=new Array()
var inc=0
var alltags=document.all? document.all : document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==classname)
ccollect[inc++]=alltags[i]
}
}
function contractcontent(omit){
var inc=0
while (ccollect[inc]){
if (ccollect[inc].id!=omit)
ccollect[inc].style.display="none"
inc++
}
}
function expandcontent(cid){
if (typeof ccollect!="undefined"){
if (collapseprevious=="yes")
contractcontent(cid)
document.getElementById(cid).style.display=(document.getElementById(cid).style.display!="block")? "block" : "none"
}
}
function revivecontent(){
contractcontent("omitnothing")
selectedItem=getselectedItem()
selectedComponents=selectedItem.split("|")
for (i=0; i<selectedComponents.length-1; i++)
document.getElementById(selectedComponents[i]).style.display="block"
}
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function getselectedItem(){
if (get_cookie(window.location.pathname) != ""){
selectedItem=get_cookie(window.location.pathname)
return selectedItem
}
else
return ""
}
function saveswitchstate(){
var inc=0, selectedItem=""
while (ccollect[inc]){
if (ccollect[inc].style.display=="block")
selectedItem+=ccollect[inc].id+"|"
inc++
}
document.cookie=window.location.pathname+"="+selectedItem
}
function do_onload(){
uniqueidn=window.location.pathname+"firsttimeload"
getElementbyClass("switchcontent")
if (enablepersist=="on" && typeof ccollect!="undefined"){
document.cookie=(get_cookie(uniqueidn)=="")? uniqueidn+"=1" : uniqueidn+"=0"
firsttimeload=(get_cookie(uniqueidn)==1)? 1 : 0 //check if this is 1st page load
if (!firsttimeload)
revivecontent()
}
}
if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload
if (enablepersist=="on" && document.getElementById)
window.onunload=saveswitchstate
</script>
<title>Søgning</title>
<link href="stylesheet/stylesheet.css" rel="stylesheet" type="text/css" />
<link rel="SHORTCUT ICON" href="images/icon.ico"/>
<script type="text/javascript" charset="utf-8" src="jquery/jquery-1.7.min.js"></script>
<script language="vbscript">
Dim conn 'GLOBAL doing this here so that all functions can use it
sub dotheconnection
Set conn = CreateObject("ADODB.Connection")
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source =./Database/data.mdb; User Id=; Password="
If conn.errors.count <> 0 Then
else
' if connected OK call sub getdata
getdata
end if
end sub
sub getdata
SQL_query = "SELECT * FROM dvd ORDER BY Title"
Set rsData = conn.Execute(SQL_query)
strHTML = strHTML & ""
Do Until rsData.EOF = True
strHTML = strHTML & "<table width='97%' border='0' id='bodytext' style='border-bottom: solid #000000 1px;'><tr><td width='70%' style='cursor: pointer'><span id='vis'><b>" & rsData("Title") & "</b></span></td><td align='right' style='color: #000'>" & rsData("Cat") & " <a href='#' onclick='editUser("& rsData("ID") &")' language='vbscript'><img src='images/arrow-blue.png' border='0' title='Rediger notatet' /></a> <a href='#' onclick='deleteUser("& rsData("ID") &")' language='vbscript'><img src='images/slet.png' border='0' title='Slet notatet' /></a></td><tr><td colspan='2'><span id='vis1'>" & rsData("Notes") & "</span></td></tr></table>"
rsData.moveNext ' go to next record
Loop
strHTML = strHTML & ""
SQL_query = "SELECT Count(*) AS intTotal FROM dvd"
Set rsData = conn.Execute(SQL_query)
strHTML1 = strHTML1 & ""
strHTML1 = strHTML1 & "" & rsData("intTotal") & " "
Count.innerHTML = strHTML1
end sub
sub searchdata
SQL_query = "SELECT * FROM dvd WHERE Title LIKE '%"& txtsrch.value &"%' OR Notes LIKE '%"& txtsrch.value &"%' ORDER BY Title"
Set rsData = conn.Execute(SQL_query)
strHTML2 = strHTML2 & ""
Do Until rsData.EOF = True
strHTML2 = strHTML2 & "<table width='97%' border='0' id='bodytext' style='border-bottom: solid #000000 1px;'><tr><span class'togglelink'><td width='70%' style='cursor: pointer'><b>" & rsData("Title") & "</b></td></span><td align='right' style='color: #000'>" & rsData("Cat") & " <a href='#' onclick='editUser("& rsData("ID") &")' language='vbscript'><img src='images/arrow-blue.png' border='0' title='Rediger notatet' /></a> <a href='#' onclick='deleteUser("& rsData("ID") &")' language='vbscript'><img src='images/slet.png' border='0' title='Slet notatet' /></a></td><tr><span class='toggle' style='display: block'><td colspan='2'>" & rsData("Notes") & "</td></span></tr></table>"
rsData.moveNext ' go to next record
Loop
strHTML2 = strHTML2 & ""
searchIT.innerHTML = strHTML2
end sub
sub deleteUser(id)
If MsgBox("Vil du slettet dette notat?", vbYesNo) =vbYes Then
SQL_query = "DELETE * FROM dvd WHERE ID = " & id
conn.Execute(SQL_query)
getdata
reloadpage()
Else
MsgBox("Notatet er ikke blevet slettet.")
End IF
end sub
sub addUser
SQL_query = "INSERT INTO dvd (Title,Length,Notes,Cat) VALUES ('"& txtTitle.value &"','"& txtLength.value &"','"& txtNotes.value &"','"& txtCat.value &"')"
conn.Execute(SQL_query)
reloadpage()
expandcontent("sc2")
getdata
end sub
sub editUser(id)
SQL_query = "SELECT * FROM dvd WHERE ID=" & id
Set rsData=conn.Execute(SQL_query)
txtTitle.value = rsData("Title")
txtLength.value = rsData("Length")
txtNotes.value = rsData("Notes")
txtCat.value = rsData("Cat")
txtID.value = rsData("ID")
btnUpdate.disabled = false // Show
btnOpret.disabled = true // Hide
expandcontent("sc2")
getdata
end sub
sub updateUser
SQL_query = "UPDATE dvd SET Title='"& txtTitle.value &"', Length='"& txtLength.value &"' , Notes='"& txtNotes.value &"', Cat='"& txtCat.value &"' WHERE ID= " & txtID.value
conn.Execute(SQL_query)
getdata
reloadpage()
expandcontent("sc2")
end sub
</script>
<script type="text/javascript" charset="utf-8" src="jquery/jquery-1.7.min.js"></script>
<SCRIPT TYPE="text/javascript">
function init()
{
dotheconnection();
searchdata();
getdata();
}
</SCRIPT>
<script>
function addNotat() {
btnOpret.disabled = false; // Show
btnUpdate.disabled = true; // Hide
expandcontent("sc2");
}
</script>
<script>
function reloadpage() {
location.reload();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$('.toggle').hide();
$('div.togglelink').on('click', function (e) {
e.preventDefault();
var elem = $(this).next('.toggle')
$('.toggle').not(elem).hide('fast');
elem.toggle('fast');
});
});
</script>
</head>
<body onLoad="init()" language="vbscript">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="40" width="20%" id="top_bar">
<input language="vbscript" onload="searchdata" onkeyup="searchdata" name="txtsrch" id="filter_input" width="15%" tabindex="0" autofocus="autofocus" size="35" type="search" style="background: url(images/search_bg.png) #FFF no-repeat left; padding-left: 20px; margin-left: 10px" placeholder="Søgning"> </td>
<td id="top_bar"></div><span id="Count"></span> notater </td>
<td width="22%" id="top_bar" align="right"><input type="button" style="margin-right: 10px" onClick="history.go(0)" value="Opdater"><a onClick="addNotat()" style="cursor: hand">Opret</a> </span></td>
<td width="20%" id="top_bar" align="right"><img src="images/footer-logo.png" style="margin-right: 10px" border="0" title="Gå til forsiden" /></td>
</tr>
</table>
<br>
<div id="sc2" class="switchcontent" style="margin-left: 10px">
<b>Title:<br></b><input type="text" name="txtTitle" size="43"><br>
<b>Kategori:</b><br>
<select size="1" name="txtCat">
<option value="">Vælg kategori</option>
<option value="Thriller">Thriller</option>
<option value="Westerns">Westerns</option>
</select><br>
<b>Length</b><br><input type="text" name="txtLength" size="8"><br>
<b>Notat:</b><br><textarea rows="6" name="txtNotes" cols="55"></textarea><br>
<p align="left"><b>
<input type="button" name="btnOpret" value="Opret" onclick="addUser" language="vbscript" disabled>
<input type="button" name="btnUpdate" value="Gem" onclick="updateUser" language="vbscript" disabled>
<input type="hidden" name="txtID">
</b></p>
</div>
</div>
<div id="searchIT" style="margin-left: 10px"></div>
</body>
</script>
</html>
The div.togglelink's will be attached after the document has been loaded, your on-handler will only have an effect to elements that are present when the document loads.
Attach the handler to the body instead:
$('body').on('click','span.togglelink',function(){/*your callback*/});

Categories