Dynamic nested tabs using php and mysql - javascript

I am a biginner to php and mysql coding. I am trying to create nested tabs dynamically.
I have created nested tabs using html, css, js. I mentioned the code below for the same. My question is how to achieve the same result dynamically using php and mysql.
Can anyone please tell me the php code for nested tabs.
Thanks in advance!!
$(".stock li:first").addClass("current");
$(".tab-inhalt:first").fadeIn();
$(".tab-content:first").fadeIn();
$(".plaene a").click(function(event) {
event.preventDefault();
$(this).parent().addClass("current");
$(this).parent().siblings().removeClass("current");
var tab = $(this).attr("href");
$(".tab-content").not(tab).css("display", "none");
$(tab).fadeIn();
$("li:first a",tab).click();
});
$(".reiter a").click(function(event) {
event.preventDefault();
$(this).parent().addClass("current");
$(this).parent().siblings().removeClass("current");
var tab = $(this).attr("href");
$(".tab-inhalt").not(tab).css("display", "none");
$(tab).fadeIn();
});
.tab-content,
.tab-inhalt {
display: none;
}
.stock li {
text-decoration: none;
list-style: none;
display: inline-block;
margin: 0 20px 0 0;
}
.stock a {
color: #0094cd;
text-decoration: none;
list-style: none;
}
.stock li.current a {
color: #4c565c;
}
.plaene a.current {
color: #4c565c;
}
.tab-alles {
width: 100%;
background-color: #f1f2f4;
margin-top: 15px;
}
.tab-oben li {
text-decoration: none;
list-style: none;
display: inline-block;
margin: 0;
background-color: #f1f2f4;
}
.tab-oben a {
color: #0094cd;
text-decoration: none;
list-style: none;
padding: 14px 20px;
display: block;
}
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<div class="stock">
<ul class="plaene">
<li class="current">Tab1</li>
<li class="">Tab2</li>
<li class="">Tab3</li>
</ul>
</div> <!-- End: .stock -->
<div class="tab-alles">
<div class="tab-oben">
<div id="objecttabs1" class="tab-content">
<ul class="reiter">
<li class="current">InnerTab1</li>
<li>InnerTab2</li>
</ul>
</div>
<div id="objecttabs2" class="tab-content">
<ul class="reiter">
<li class="">InnerTab1</li>
<li>InnerTab2</li>
</ul>
</div>
<div id="objecttabs3" class="tab-content">
<ul class="reiter">
<li>InnerTab1</li>
<li>InnerTab2</li>
</ul>
</div>
</div> <!-- End: .tab-oben -->
<div class="tab-inhalt-all">
<div id="innertab1" class="tab-inhalt">
<div class="content">Content1</div>
</div>
<div id="innertab2" class="tab-inhalt">
<div class="content">Content2</div>
</div>
<div id="innertab3" class="tab-inhalt">
<div class="content">Content3</div>
</div>
<div id="innertab4" class="tab-inhalt">
<div class="content">Content4</div>
</div>
<div id="innertab5" class="tab-inhalt">
<div class="content">Content5</div>
</div>
<div id="innertab6" class="tab-inhalt">
<div class="content">Content6</div>
</div>
</div> <!-- End: .tab-inhalt-all -->

Unfortunately, I do not have enough reputation to leave a comment. So the only way to help you out is like this.
If you want to "generate" these tabs automatically using PHP (and MySQL?) you could do the following: (if you need help on the MySQL part as well, drop a comment and I'll edit this)
here's a we-transfer link you can download an example database from for your tabs:
https://wetransfer.com/downloads/09eedb2dd16806841befe2b7701f3fab20210325114020/d426c8
The PHP, HTML, and JS:
<?php
$servername = "";//location of the database
$username = "";//username to access
$password= "";//password to access
$dbname = "Tabs";//database you want to access
//establish connection:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//get the data from the db
$output = sqlStringGetAsArray($conn, "SELECT * FROM Tabs");//This is the "Tabs" table in the "Tabs" database
function sqlStringGetAsArray($conn, $sql=""){
$result = $conn->query($sql);
if ($conn->error){
return false;
}
$array = [];
$headers=$result->fetch_fields();
$top = [];
foreach ($headers as $header){
$name = $header->name;
array_push($top, $name);
}
array_push($array,$top);
while ($row = $result->fetch_row()){
array_push($array, $row);
}
return $array;
}
//set the output to the format we need to display:
$tabContents = [];
$first = true;
foreach($output as $val){
if($first){
$first = false;
}else{
if(!isset($tabContents[$val[1]])){
$tabContents[$val[1]] = [];
}
array_push($tabContents[$val[1]], [$val[2], $val[3]]);
}
}
?>
<html>
<head>
<link rel='stylesheet' href='./tabs.css'>
</head>
<body>
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<div id='container'>
<div class='Tabs'>
<?php
$i1 = 0;
foreach($tabContents as $key=>$value){
if($i1==0){
echo"<div id='Tab".$i1."' class='level1 active' onclick='updateTabs(this)'>".$key."</div>";
}else{
echo"<div id='Tab".$i1."' class='level1' onclick='updateTabs(this)'>".$key."</div>";
}
$i1++;
}
?>
</div>
<div class='innerTabs'>
<?php
$i1 = 0;
foreach($tabContents as $key=>$value){
$i2 = 0;
if($i1 == 0){
echo("<div id='Tab".$i1."' class='parent visible'>");
foreach($value as $i){
if($i2 == 0){
echo"<div id='innerTab".$i2."' class='level2 active' onclick='updateInnerTabs(this)'>".$i[0]."</div>";
}else{
echo"<div id='innerTab".$i2."' class='level2' onclick='updateInnerTabs(this)'>".$i[0]."</div>";
}
$i2++;
}
$i1++;
}else{
echo("<div id='Tab".$i1."' class='parent'>");
foreach($value as $i){
if($i2 == 0){
echo"<div id='innerTab".$i2."' class='level2 active' onclick='updateInnerTabs(this)'>".$i[0]."</div>";
}else{
echo"<div id='innerTab".$i2."' class='level2' onclick='updateInnerTabs(this)'>".$i[0]."</div>";
}
$i2++;
}
$i1++;
}
echo("</div>");
}
?>
</div>
<div class='contents'>
<?php
$i1 = 0;
foreach($tabContents as $key=>$value){
$i2 = 0;
foreach($value as $i){
if($i1 == 0 && $i2 == 0){
echo"<div id='Tab".$i1."_innerTab".$i2."_content' class='level3 visible'>".$i[1]."</div>";
}else{
echo"<div id='Tab".$i1."_innerTab".$i2."_content' class='level3'>".$i[1]."</div>";
}
$i2++;
}
$i1++;
}
?>
</div>
</div>
<script>
function updateTabs(el) {
visibility(el, '.innerTabs');
$('.innerTabs').children('#' + $(el).attr('id')).addClass('visible');
updateInnerTabs($('.innerTabs').children('#' + $(el).attr('id')).children().first());
}
function updateInnerTabs(el) {
visibility(el, '.contents');
var tab = $(el).parent().attr('id') + '_';;
var innerTab = $(el).attr('id') + '_content';
$('#' + tab + innerTab).addClass('visible');
}
function visibility(el, aClass) {
$(el).siblings('.active').removeClass('active');
$(el).addClass('active');
$(aClass).children('.visible').removeClass('visible');
}
</script>
(This bit is at the bottom of the file:)
<pre>
<?php
print_r($tabContents);
?>
</pre>
</body>
</html>
the CSS:
.Tabs{
background-color: #222;
}
.level1{
padding: 16px;
color: #eee;
background-color: #222;
display: inline-block;
}
.level1.active{
color: #fff;
background-color: #4caf50;
display: inline-block;
}
.level1:hover{
color: #000;
background-color: #eee;
}
.innerTabs{
background-color: #444;
color: #eee;
}
.parent:not(.visible){
display: none;
}
.level2{
padding: 16px;
background-color: #444;
color: #fff;
display: inline-block;
}
.level2.active{
color: #fff;
background-color: #65bd68;
display: inline-block;
}
.level2:hover{
color: #000;
background-color: #eee;
display: inline-block;
}
.contents{
background-color: #ddd;
color: #000;
padding: 16px;
}
.contents div:not(.visible){
display: none;
}
Although this code is not very elegant, it gets the job done, and you can easily get Data from your Database and put it into $tabContents.
One way you could organize your table would be like so:
Bear in mind that the "Tab" value has to be the same for some if you want multiple "innerTabs" for a "tab". This example will have 1 "Tab" with 2 "innerTabs"

Related

Wordpress - Highlight nav links on scroll

I was able to successfully add code to my script.js file so that the links in the nav section would highlight as you scrolled down the page.
But ever since I converted my webpage into a wordpress template, the javascript that allowed the highlighting nav links no longer works.
I have played around w/ the code to try and get it to work again, but nothing works.
I do not know how this is supposed to work now that I am attempting to do the same thing in wordpress.
Below is the old code. Any help is greatly appreciated.
/* Script.js */
const sections = document.querySelectorAll('section');
const navLi = document.querySelectorAll('nav .container ul li');
window.addEventListener('scroll', () => {
let current = '';
sections.forEach( section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (pageYOffset >= sectionTop) {
current = section.getAttribute('id');
}
});
navLi.forEach( li => {
if (pageYOffset <= 1710) {
li.classList.remove('active-section');
if( li.classList.contains(current) ) {
li.classList.add('active-section');
}
} else {
current = 'contact';
li.classList.remove('active-section');
if( li.classList.contains(current = 'contact') ) {
li.classList.add('active-section');
}
}
});
});
<!-- header.php -->
<nav id="nav" <?php echo (is_admin_bar_showing()) ? ' style="top: 32px;" ' : ''; ?>>
<div class="container">
<!-- hamburger menu -->
<input type="checkbox" id="check">
<label for="check" class="checkbtn">
<i class="fas fa-bars"></i>
</label>
<!-- nav-logo -->
<p id="logo">lf</p>
<!-- nav links -->
<?php
//
if( has_nav_menu( "port-nav-menu" )) {
wp_nav_menu(array(
"theme_location" => "port-nav-menu",
"container" => ""
));
}
?>
</div>
</nav>
/* style.css */
nav {
display: flex;
position: fixed;
text-transform: uppercase;
top: 0%;
width: 100%;
z-index: 1;
}
nav a:link, nav a:visited {
color: #ffffff;
text-decoration: none;
}
nav .container ul li.active-section {
background: #e31b6d;
}
nav a:hover {
color: #e31b6d;
}
nav ul {
display: flex;
float: right;
line-height: 50px;
list-style-type: none;
margin: auto;
}

change a div properties in php side

I'm making a simple Php and javascript project where my css design has some overlay design in it. Now I have a button when clicked it displays an overlay div named "myNav" where a div named "req_form" and form are on it where users can fill out inputs and submit them, then my php code will store those data in my database. I just can't figure out how to replace the div and dislpay success on it after successfully submitting the data in my Php code.
my overlay div
<?php
include 'includes/autoloader.inc.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function openNav() {
document.getElementById("myNav").style.width="100%";
}
function closeNav(){
document.getElementById("myNav").style.width = "0";
}
</script>
<link rel="stylesheet" type="text/css" href="css/cssticket.css">
</head>
<body>
<button class="button_a" onclick="openNav()">Create Request</button> //OPENS THE OVERLAY DIV
<div id="myNav" class="overlay"> // THIS IS THE OVERLAY DIV
×
<div class="overlay-content">
<div id="req_form" class="inputs"> // THIS IS THE DIV I WANT TO BE REPLACE BY A MESSAGE SUCCESS
<div id="error"></div>
<form id="form" action="includes/enduser.inc.php" method="POST">
<input type="text" name="userrequester" placeholder="name" >
<br>
<label for="reqtype">Request type:</label>
<select name="priority" required>
<option value="">Select</option>
<option value="High">General</option>
<option value="Low">Urgent</option>
</select>
<br>
<label for="itemtype">Item type:</label>
<input type="radio" name="typeitem" value="Borrowed" required><label>Borrowed</label>
<input type="radio" name="typeitem" value="Replace" required></input><label>Replace</label>
<br>
<label>Summary :</label>
<br>
<textarea name="summary" cols="30" rows="10" required ></textarea>
<br>
<button type="submit" name="sendrequest" class="button_a">Submit</button>
</div>
</form>
</div>
</div>
</body>
</html>
here is my php file :
include 'autoloader.inc.php';
$request = new usercontlr;
if (isset($_POST['sendrequest'])) {
$date = date ('F d, Y');
$enduser = $_POST['userrequester'];
$priority = $_POST["priority"];
$itemtype = $_POST["typeitem"];
$summary = $_POST["summary"];
$status = "new";
$request->createticket($enduser, $priority, $itemtype, $status, $summary, $date); // function where my object stores data in my database
What i have tried already is to echo out some javascript that should have change the into a success message after storing the data inside this php file.
echo ' <script type="text/javascript">
document.getElementById('req_form').style.display = "none";
var h1 = document.createElement('h1');
var result = document.createTextNode('Success!');
h1.appendChild(result);
document.getElementById('myNav').appendChild(h1);
</script> ' ;
but when I check the console I got an error (enduser.inc.php:3 Uncaught TypeError: Cannot read property 'style' of null
at enduser.inc.php:3
(anonymous) # enduser.inc.php:3)
Here is also my css if it helps:
.inputs {
padding: 20px;
display: inline-block
}
.overlay {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: rgb(11, 156, 49);
background-color: rgba(11, 156, 49, 0.9);
overflow-x: hidden;
transition: 0.5s;
}
.overlay-content {
font-family: monospace;
font-size: 15px;
background-color: white;
border-radius: 2%;
position: relative;
top: 25%;
width: 50%;
margin: 0 auto;
text-align: center;
}
.overlay a {
padding: 8px;
text-decoration: none;
font-size: 36px;
color: #818181;
display: block;
transition: 0.3s;
}
.overlay a:hover,
.overlay a:focus {
color: red;
}
.overlay .closebtn {
color: white;
position: absolute;
top: 20px;
right: 45px;
font-size: 60px;
}
#media screen and (max-height: 450px) {
.overlay a {
font-size: 20px
}
.overlay .closebtn {
font-size: 40px;
top: 15px;
right: 35px;
}
}
You will want to create a header() redirect to your original page once you have successfully queried and successfully added your inputs to the DB.
Something like this:
if (isset($_POST['sendrequest'])) {
$date = date ('F d, Y');
$enduser = $_POST['userrequester'];
$priority = $_POST["priority"];
$itemtype = $_POST["typeitem"];
$summary = $_POST["summary"];
$status = "new";
// Pretty sure this can be wrapped in your if statement, may need to test that.
// --> $request->createticket($enduser, $priority, $itemtype, $status, $summary, $date);
if($request->createticket($enduser, $priority, $itemtype, $status, $summary, $date)){
$postMSG = "success"; // sending the success message over url as $_GET
$host = $_SERVER['HTTP_HOST']; // SERVER
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Directory
$extra = 'ticketformpage.php'; // the page your form is on
header("Location: http://$host$uri/$extra?$postMSG"); // header redirect with url post added
}
Now on the page you wish to display the success message, we check to see if the GET global isset with success $_GET['success'] if it is then we set the variable and display them and add some css.
<?php
$msg = NULL; // we set to NULL for when the message is not needed
if(isset($_GET['success'])){
$msg = "Thank you for submitting through our ticket system.";
}else{
$msg = NULL;
}
NOTE: I added the success in a <span> tag and added padding and border radius, limegreen bg and darkgreen color to associate with success. 10px margin-top for form.
<div id="req_form" class="inputs">
<span class="success"><?=$msg?></span> <!--// add the success variable here-->
<div id="error"></div>
<form id="form" action="inputtest.php" method="POST">
CSS:
form {
margin-top: 10px;
}
.success {
background-color: limegreen;
color: darkgreen;
padding: 10px;
border-radius: 5px;
}

PHP & JS - Connection, Error Messages and Redirecting

I pretty much finish my job, everything works except redirecting and now I will show it to you.
So, I have a website, set up with HTML, CSS, PHP, MySqli and in the end (How weird it shouldn't sound) I planned to add some JS.
I need to finish up my Login form, everything seems to work correctly.
HTML + CSS + JS Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<style>
#form-mes1{
background-color: rgb(255, 232, 232);
border: 1px solid red;
color: red;
display: none;
font-size: 12px;
font-weight: bold;
margin-bottom: 20px;
padding: 15px 25px;
max-width: 450px;
}
</style>
<body>
<header>
<div class="container1">
<img src="img/header.png" alt="logo" class="logo">
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Services
<li>Contact</li>
<li>Profile</li>
</ul>
</nav>
</div>
</header>
<div class="container3">
<form class="login-form2" method="post" action="login.php">
<ul id="form-mes1">
<li>Generic Error #1</li>
</ul>
<label for="email">E-Mail</label>
<input type="email" id="email" name="logemail" class="input">
<label for="password">Password</label>
<input type="password" id="password" name="logpassword" class="input">
<button type="submit" id="btn_submit" name="sButton" class="btn2">LOGIN</button>
</form>
</div>
<script>
const container3 = {
email: document.getElementByID('email'),
password: document.getElementByID('password'),
submit: document.getElementByID('btn_submit'),
messages: document.getElementByID('form-mes1')
};
container3.submit.addEventListener('click', () => {
const request = new XMLHttpRequest();
request.onload = () => {
let responseObject = null;
try{
responseObject = JSON.parse(request.responseText);
}catch(e){
console.error('Cannot Pass JSON');
}
if(responseObject){
handleResponse(responseObject);
}
};
const requestData = `email=${container3.email.value}&password=${container3.password.value}`;
request.open('post', 'login.php');
request.setRequestHeader('Content-type', 'application/x-www-form-urldecoded');
request.send(requestData);
});
function handleResponse(responseObject){
if(responseObject.ok){
location.href = 'dashboard.html';
}else{
while(form.messages.firstChild){
form.messages.removeChild(container3.messages.firstChild);
}
responseObject.messages.forEach((message) => {
const li = document.createElement('li');
li.textContent = message;
container3.messages.appendChild(li);
});
container3.messages.style.display = "block";
}
}
</script>
</body>
Here is my PHP code:
<?php
$ok = true;
$messages = array();
if(isset($_POST['sButton'])){
if(empty($_POST['logemail']) or empty($_POST['logpassword'])){
$ok = false;
$messages[] = "Values Can't Be Empty";
}elseif($ok){
$email = $_POST['logemail'];
$password = $_POST['logpassword'];
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($conn, "car_accs");
$query = mysqli_query($conn, "SELECT * FROM accounts WHERE Mail = '$email' AND Password = '$password'");
$rows = mysqli_num_rows($query);
if($rows == 1){
$ok = true;
$messages[] = "Successful Log In";
}else{
$ok = false;
$messages[] = "Failed To Log In";
}
mysqli_close($conn);
}
}
echo json_encode(
array(
'ok' => $ok,
'messages' => $messages
)
);
?>
Everything works, if I miss out mail or password I get message:
If I write incorrect data I get the same type message:
{"ok":false,"messages":["Failed To Log In"]}
And If I log in successfully, this message:
{"ok":true,"messages":["Successful Log In"]}
But the idea is that if I log in successfully, I need to be redirected as you see in the JS code, if not than I have a display box which shows errors in a red box.
Something goes wrong and JS code almost doesn't work and I don't understand why, any help will be just amazing.
So the problem was in the contact between the JS and HTML.
First problem was about DIV that I created, which couldn't use addEventListener property, as well as with the inputs, I used both ID and Class and it was a mistake and program just didn't continue to work it was on break.
After changing both DIV and inputs to only ID option (Needed to write CSS right in to the HTML file) I wrote the JS code once again and everything went perfectly.
Here is the code HTML + CSS + JS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<style>
.form{
background-color: white;
box-sizing: border-box;
padding: 40px;
clear: both;
height: 550px;
width: 450px;
margin: 100px auto;
color: #24E7B9;
font-size: 18px;
}
#form-messages{
background-color: rgb(255, 232, 232);
border: 1px solid red;
color: red;
display: none;
font-size: 12px;
font-weight: bold;
margin-bottom: 20px;
padding: 15px 25px;
max-width: 450px;
}
#mail,
#pass{
width: 100%;
box-sizing: border-box;
padding: 20px;
margin-bottom: 25px;
border: 2px solid #24E7B9;
color: black;
font-size: 16px;
outline: none;
transition: all 0.5s ease;
}
#btn-submit{
width: 100%;
background-color: #24E7B9;
height: 60px;
text-align: center;
line-height: 60px;
text-transform: uppercase;
color: white;
font-weight: bold;
letter-spacing: 1px;
margin-bottom: 10px;
cursor: pointer;
}
</style>
<body>
<header>
<div class="container1">
<img src="img/header.png" alt="logo" class="logo">
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Services
<li>Contact</li>
<li>Profile</li>
</ul>
</nav>
</div>
</header>
<div class="form">
<ul id="form-messages"></ul>
<label for="mail">E-Mail</label>
<input type="mail" id="mail">
<label for="pass">Password</label>
<input type="password" id="pass">
<button type="submit" id="btn-submit">Login</button>
</div>
<script>
const form = {
mail: document.getElementById('mail'),
pass: document.getElementById('pass'),
submit: document.getElementById('btn-submit'),
messages: document.getElementById('form-messages')
};
form.submit.addEventListener('click', () => {
const request = new XMLHttpRequest();
request.onload = () => {
let responseObject = null;
try{
responseObject = JSON.parse(request.responseText);
}catch(e){
console.error('Could Not Pass JSON');
}
if(responseObject){
handleResponse(responseObject);
}
};
const requestData = `mail=${form.mail.value}&pass=${form.pass.value}`;
request.open('post', 'login.php');
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.send(requestData);
});
function handleResponse(responseObject){
if(responseObject.ok){
location.href = 'dashboard.html';
}else{
while(form.messages.firstChild){
form.messages.removeChild(form.messages.firstChild);
}
responseObject.messages.forEach((message) => {
const li = document.createElement('li');
li.textContent = message;
form.messages.appendChild(li);
});
form.messages.style.display = "block";
}
}
</script>
</body>
Here is the PHP code:
<?php
$mail = isset($_POST['mail']) ? $_POST['mail'] : '';
$pass = isset($_POST['pass']) ? $_POST['pass'] : '';
$ok = true;
$messages = array();
if(!isset($mail) OR empty($mail)){
$ok = false;
$messages[] = 'Mail Cannot Be Empty';
}
if(!isset($pass) OR empty($pass)){
$ok = false;
$messages[] = 'Password Cannot Be Empty';
}
if($ok){
$mail = $_POST['mail'];
$pass = $_POST['pass'];
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($conn, "car_accs");
$query = mysqli_query($conn, "SELECT * FROM accounts WHERE Mail = '$mail' AND Password = '$pass'");
$rows = mysqli_num_rows($query);
if($rows == 1){
$ok = true;
$messages[] = "Successful Log In";
}else{
$ok = false;
$messages[] = "Failed To Log In";
}
mysqli_close($conn);
}
echo json_encode(
array(
'ok' => $ok,
'messages' => $messages
)
);
?>
Redirecting and connection problems are solved. Thank you everybody.

Onclick javascript function doesn't work on first click

I've wrote a code to hide/show a div by clicking on a "p" element, but at first click nothing happens.
Only from 2nd click the code works as expected.
I've read some similar questions and I've understood that it's probably a style problem.
So I've tried to change style (without really knowing what I was doing) but I wasn't lucky.
I've also another problem: the "p" element sometimes covers an input and I've not understood how to have it on the bottom right of the div but below every other element.
<!DOCTYPE html>
<html>
<head>
<style>
.Class1 {
position:relative;
display: inline-block;
width: 48%;
margin: 3px;
border: 3px solid #CCC;
}
.Class2 {
position:absolute;
bottom:0;
right:0;
border: 1px solid #CCC;
margin:1px;
background: #FFC;
}
.Fields {
clear: both;
border: 1px solid #CCC;
display: inline-block;
margin:3px;
}
.H_p {
border: 1px solid #CCC;
display: inline-block;
}
.Opt {
border: 1px solid #CCC;
display: none;
}
</style>
</head>
<body>
<h2>My test</h2>
<?php
$Divs = array('Div1'=>'Class1',
'Div2'=>'Class1',
'Div3'=>'Class1',
'Div4'=>'Class1',
'Div5'=>'Class1');
$AskToShow=array("Field1"=>"1.1.1", "Field2"=>"1.2.1", "Field3"=>"1.3.1");
foreach ($Divs as $Name=>$Class){
echo '
<div class="'.$Class.'">';
echo $Name.'<br/>';
foreach ($AskToShow as $I_Name=>$Id){
echo '
<label>'.$I_Name.'</label>
<input type="text" id="'.$Id.'" class="Fields"/>';
}
echo '
<p id="Btn_Opt'.$Name.'" class="Class2" >Mostra campi opzionali</p>';
echo '
<div id=Opt'.$Name.' name="Opt'.$Name.'" class="Opt" >';
foreach ($AskToShow as $H_Name=>$Id){
echo'
<p id="H_'.$Id.'" class="H_p">'.$H_Name.'</p>';
}
echo '
</div>';
echo '
</div>';
}
?>
<script>
var MyClass = document.getElementsByClassName("Class2");
var myFunction = function() {
var SenderId = this.id;
var SubId = SenderId.substring(SenderId.indexOf('_')+1)
var SubSH = document.getElementById(SubId);
if (SubSH.style.display == 'none'){
SubSH.style.display = 'inline-block';
}else{
SubSH.style.display = 'none';
}
};
for (var i = 0; i < MyClass.length; i++) {
MyClass[i].addEventListener('click', myFunction, false);
}
</script>
</body>
</html>
The thing is that when you do SubSH.style.display you are checking only inline style so something which is inn <your-tag style='...'/> but you have it in your stylesheet so it is not accessible by this method. try to change your function a bit - for example
var myFunction = function() {
var SenderId = this.id;
var SubId = SenderId.substring(SenderId.indexOf('_')+1)
var SubSH = document.getElementById(SubId);
var style = window.getComputedStyle(SubSH);
if (style.display == 'none'){
SubSH.style.display = 'inline-block';
}else{
SubSH.style.display = 'none';
}
};
by using window.getComputedStyle(SubSH); you are checking style which is aware of all your classes and csses
Please find the working code below
<!DOCTYPE html>
<html>
<head>
<style>
.Class1 {
position:relative;
display: inline-block;
width: 48%;
margin: 3px;
border: 3px solid #CCC;
}
.Class2 {
position:relative;
bottom:0;
right:0;
border: 1px solid #CCC;
margin:1px;
background: #FFC;
display: inline-block;
float:right;
}
.Fields {
clear: both;
border: 1px solid #CCC;
display: inline-block;
margin:3px;
}
.H_p {
border: 1px solid #CCC;
display: inline-block;
}
.Opt {
border: 1px solid #CCC;
display: none;
}
</style>
</head>
<body>
<h2>My test</h2>
<?php
$Divs = array(
'Div1' => 'Class1',
'Div2' => 'Class1',
'Div3' => 'Class1',
'Div4' => 'Class1',
'Div5' => 'Class1'
);
$AskToShow = array(
"Field1" => "1.1.1",
"Field2" => "1.2.1",
"Field3" => "1.3.1"
);
foreach ($Divs as $Name => $Class) {
echo '
<div class="' . $Class . '">';
echo $Name . '<br/>';
foreach ($AskToShow as $I_Name => $Id) {
echo '
<label>' . $I_Name . '</label>
<input type="text" id="' . $Id . '" class="Fields"/>';
}
echo '
<div id=Opt' . $Name . ' name="Opt' . $Name . '" class="Opt" >';
foreach ($AskToShow as $H_Name => $Id) {
echo '
<p id="H_' . $Id . '" class="H_p">' . $H_Name . '</p>';
}
echo '
</div>';
echo '
<div style="clear:both;"></div>';
echo '
<p id="Btn_Opt' . $Name . '" class="Class2" >Mostra campi opzionali</p>';
echo '
</div>';
}
?>
<script>
var MyClass = document.getElementsByClassName("Class2");
var myFunction = function() {
var SenderId = this.id;
var SubId = SenderId.substring(SenderId.indexOf('_')+1)
var SubSH = document.getElementById(SubId);
if (window.getComputedStyle(SubSH, null).display == 'none'){
SubSH.style.display = 'inline-block';
} else {
SubSH.style.display = 'none';
}
};
for (var i = 0; i < MyClass.length; i++) {
MyClass[i].addEventListener('click', myFunction, false);
}
</script>
</body>
</html>

PhoneGap javascript reference issue

In my PhoneGap Eclipse project I am using jQuery for visual effects by referencing jQuery libraries:
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript"
src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.js"></script>
and I am also making remote domain requests in order to display some information from the remote server.
1: When I make requests to multiple servers, I get an error saying:
DroidGap: TIMEOUT ERROR! - calling webViewClient
I read that I must alter my Phonegaps whitelist by doing:
<phonegap>
<access origin="\*\" />
</phonegap>
Source: GitHub call-back
But I get some error, so I have decided to approach same results from the different ways:
2: <script type="text/javascript" src="file:///android_asset/js/jquery.js"></script>
<script type="text/javascript" src="../js/jquery.js"></script>
Why? - because i would like to avoid getting errors with multiple-domain requests
In these cases I get an error
SyntaxError: Parse error at file:///... in logcat
I have no idea why this is happening, because the specified file location supposed to be right in both cases.
So my questions are:
Why I cannot include .js file in this way?
Which solution I should continue trying to approach (1 or 2)?
<html>
<head>
<title></title>
<script src="phonegap-1.3.0.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.0.css" />
<script type="text/javascript" src="jquery.mobile-1.0.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<!--
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="lib/touch/resources/css/sencha-touch.css" type="text/css">
<script type="text/javascript" src="lib/touch/sencha-touch.js"></script>
<!-- <script type="text/javascript" src="lib/touch/index.js"></script> -->
<script>
var alreadyrunflag = 0 //flag to indicate whether target function has already been run
var url = "http://www.norwegian.no/";
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
//on page loaded
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", function() {
//alreadyrunflag = 1;
initGet(url);
}, false)
else if (document.all && !window.opera) {
//page load error?
}
function applyChangeEvent() {
//on selection changed
var selectDepart = document.getElementById("depart");
var selectArrive = document.getElementById("arrive");
selectDepart.onchange = function() { //run some code when "onchange" event fires
if (document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value != ""
&& document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value != "") {
for ( var monthsCount = 1; monthsCount < 13; monthsCount++) {
//alert(monthsCount);
get("http://www.norwegian.no/fly/lavpris/", monthsCount);
}
}
}
selectArrive.onchange = function() { //run some code when "onchange" event fires
if (document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value != ""
&& document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value != "") {
for ( var monthsCount = 1; monthsCount < 13; monthsCount++) {
//alert(monthsCount);
get("http://www.norwegian.no/fly/lavpris/", monthsCount);
}
}
}
}
function initGet(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
//request.responseText
getObjs(request.responseText);
}
}
}
request.send();
}
function get(url, month) {
//alert(month);
url += "?D_City="
+ document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value;
url += "&A_City="
+ document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value;
url += "&TripType=1";
url += "&D_Day=1";
url += "&D_Month=" + getMonth(month);
/* url += "&R_Day=1";
url += "&R_Month=201201"; */
url += "&AdultCount=1";
url += "&ChildCount=0";
url += "&InfantCount=0";
//alert(url);
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
//request.responseText
parse(request.responseText, month);
}
}
}
request.send();
}
function getMonth(month) {
//alert(month.toString.length + " | " + month);
if (month.toString().length == 1) {
var tempMonth = "0" + month.toString();
//alert(tempMonth);
return year.toString() + tempMonth;
} else
return year.toString() + month;
}
function getSimpleMonth() {
return month;
}
function getObjs(mainPageHtml) {
var mainDoc = (new DOMParser()).parseFromString(mainPageHtml,
"application/xhtml+xml");
var select = mainDoc.getElementsByTagName("select")[1];
var options = select.getElementsByTagName("option");
var citiesArray = [];
for ( var i = 0; i < options.length; i++) {
cityObj = new Object();
cityObj.name = options[i].text;
cityObj.value = options[i].value;
citiesArray.push(cityObj);
}
for ( var city = 0; city < citiesArray.length; city++) {
document.getElementById("depart").innerHTML += "<option value='"+citiesArray[city].value+"'>"
+ citiesArray[city].name + "</option>";
document.getElementById("arrive").innerHTML += "<option value='"+citiesArray[city].value+"'>"
+ citiesArray[city].name + "</option>";
}
applyChangeEvent();
}
function parse(html, id) {
var pricesArray = [];
//alert(id);
var resultDoc = (new DOMParser()).parseFromString(html,
"application/xhtml+xml");
var divs = resultDoc.getElementsByTagName("table");
for ( var div = 0; div < divs.length; div++) {
if (divs[div].className == "fareCalendarTable") {
//alert("found!");
// TODO: find out how many to open!!
document.getElementById(id).style.display = "block";
document.getElementById("nav_").style.display = "block";
var table = resultDoc.getElementsByTagName("table")[div];
var divs = table.getElementsByTagName("div");
//var tbodyTrs = tbody.getElementsByTagName("tr");
//alert(document.getElementById("month-one").innerHTML);
for ( var price = 0; price < divs.length; price++) {
if (divs[price].title != "") {
/* document.getElementById("month-one-results").innerHTML += divs[price].id
.replace("OutboundFareCal", "")
+ " : " + divs[price].title + "<br>"; */
priceObj = new Object();
priceObj.date = divs[price].id.replace(
"OutboundFareCal", "");
priceObj.price = divs[price].title.replace(" NOK", "");
priceObj.price.replace(/\s/g, '');
pricesArray.push(priceObj);
}
}
/* pricesArray.sort(function sortNumber(a, b) {
return parseInt(b) - parseInt(a);
}); */
for ( var priceUnit = 0; priceUnit < pricesArray.length; priceUnit++) {
document.getElementById("month-results-" + id).innerHTML += "<table><tr><td>"
+ pricesArray[priceUnit].date
+ "</td><td>"
+ pricesArray[priceUnit].price
+ "</td></tr></table>";
}
}
document.getElementById("depart").disabled = "disabled";
document.getElementById("arrive").disabled = "disabled";
}
// document.getElementById("results").innerHTML = bodybox.item(0).innerHTML;
//holy grail!
var month = document.getElementById("month-" + id);
var spans = month.getElementsByTagName("span");
for ( var span = 0; span < spans.length; span++) {
if (spans[span].className == "ui-btn-text") {
spans[span].innerHTML += "<p>" + getCheapest(pricesArray)
+ "</p>";
}
}
}
function getCheapest(pricesArray) {
pricesArray.sort(sort);
return pricesArray[1].price;
}
function sort(a, b) {
if (a.price < b.price)
return -1;
if (a.price > b.price)
return 1;
return 0;
}
function restart() {
window.location.reload();
return false;
document.getElementById("depart").removeAttribute("disabled");
document.getElementById("arrive").removeAttribute("disabled");
}
</script>
<style>
body {
display: block;
padding: 20px;
color: #3D3C2F;
font-family: Arial, Sans-Serif, Helvetica;
font-size: 12px;
font-weight: normal;
}
div#content {
margin-left: auto;
margin-right: auto;
background: #fff;
height: 100%;
-webkit-border-bottom-left-radius: 8px;
-webkit-border-bottom-right-radius: 8px;
display: block;
color: #3D3C2F;
font-family: Arial, Sans-Serif, Helvetica;
font-size: 12px;
font-weight: normal;
background-image:
url(http://www.norwegian.no/Global/backgrounds/background_no.gif);
background-repeat: repeat-x;
background-repeat-x: repeat;
background-repeat-y: no-repeat;
background-position-x: 0%;
background-position-y: 0%;
width: 100%;
padding-top: 20px;
padding-bottom: 30px;
}
div#navigation {
margin-left: auto;
margin-right: auto;
padding: 20px;
position: block;
width: 80%;
background: #CCCC00;
-webkit-border-radius: 8px;
}
select {
position: block;
width: 100%;
text-color: #000;
overflow: hidden;
}
</style>
</head>
<body>
<div id="nav_" data-role="header" data-position="inline" data-theme="e"
style="display: none;">
<a href="#" data-icon="back" data-theme="c"
onClick="window.location.reload();return false;">Start</a>
<h1>Ticket Prices</h1>
</div>
<div id="content">
<div id="navigation">
Fra/From: <select id="depart">
</select> Til/To: <select id="arrive">
</select>
</div>
<div data-role="collapsible" id="1"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-1">January</h3>
<p id="month-results-1"></p>
</div>
<div data-role="collapsible" id="2"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-2">February</h3>
<p id="month-results-2"></p>
</div>
<div data-role="collapsible" id="3"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-3">March</h3>
<p id="month-results-3"></p>
</div>
<div data-role="collapsible" id="4"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-4">April</h3>
<p id="month-results-4"></p>
</div>
<div data-role="collapsible" id="5"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-5">May</h3>
<p id="month-results-5"></p>
</div>
<div data-role="collapsible" id="6"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-6">June</h3>
<p id="month-results-6"></p>
</div>
<div data-role="collapsible" id="7"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-7">July</h3>
<p id="month-results-7"></p>
</div>
<div data-role="collapsible" id="8"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-8">August</h3>
<p id="month-results-8"></p>
</div>
<div data-role="collapsible" id="9"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-9">September</h3>
<p id="month-results-9"></p>
</div>
<div data-role="collapsible" id="10"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-10">October</h3>
<p id="month-results-10"></p>
</div>
<div data-role="collapsible" id="11"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-11">November</h3>
<p id="month-results-11"></p>
</div>
<div data-role="collapsible" id="12"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-12">December</h3>
<p id="month-results-12"></p>
</div>
</div>
<!-- <div id="results"></div> -->
</body>
</html>
If your directory structure is assets/www/js/jquery.js use :
<script type="text/javascript" src="js/jquery.js"></script>

Categories

Resources