hide span when i click on it despite the automatic page refresh - javascript

html (quotazioni.php)
<?php
$azioni = $db_handle->runQuery("SELECT idAzione,nome,prezzo FROM azioni");
foreach($azioni as $azione){
?>
<tr>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;"><?php echo $azione["nome"]; ?></td>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;"><?php echo $azione["prezzo"]; ?></td>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;">
<a href="compraVendi.php?action=segui&idAzione=<?=$azione["idAzione"]?>" id="<?=$azione["nome"]?>" style="text-decoration:none;" class="preferiti" >
<span style="color:yellow;font-size:200%;" id="<?=$azione["idAzione"]?>" >&star;</span>
</a>
</td>
</tr>
<?php
}
?>
php (compraVendi.php)
case "segui":
$db_handle->query("INSERT INTO preferiti (visibile,idAzione) VALUES (1,'".$_GET["idAzione"]."')");
header("location: quotazioni.php");
break;
javascript
$(document).ready(function(){
<?php
$preferiti = $db_handle->runQuery("SELECT * FROM preferiti");
foreach($preferiti as $preferito){
if ($preferito["visibile"]==1){
?>
var element = document.getElementById(<?=$preferito["idAzione"]?>);
element.hide();
<?php
}
}
?>
});
I must hide the span inside the link after I click on it. How do I keep the span disabled considering the page contains an automatic refresh? I provide an example of code which not work, please help me to solve the problem. In the sql database, the table preferiti contains idPreferito,visibile and idAzione. The row preferito contains 1 if i clicked on the respective prefer.

When user clicks on the the star - you need to save this data to a persistent storage, e,g your backend. This is the only way you will be able to regain this state after page refresh.
So when serving the page to the client, you will consider another field, for example 'disabled' which contains string 'disabled'
It could be something like this:
<a href="#" id="<?=$azione["nome"]?>" class="preferiti" >
<span class="favourites-star <?=$azione["disabled"]?>" id="<?=$azione["idAzione"]?>" >&star;</span>
</a>
Consider not using insline styles and instead using classes for styling - this is a general good practice.
.favourites-star {
color:yellow;
font-size:200%;
}
Classes are also better when dealing with events.
$(document).ready(function(){
$('.prefereti').on('click', function(evt){
// Save the state first and then disable the star - try it yourself!
$.post()
.done(function () {
$(evt.currentTarget).addClass('disable');
})
.fail(function () {
// Don't disable - instead show error
});
});
});
One more thing that you need to keep in mind while the state is being saved, your page might reload - so you might like to prohibit it from reloading for that time.

Related

Give a GET value to a javascript Pop Up

I'm currently working on a page which loops some content. When you click on the image, more information appears in a javascript popup. I want to give every popup an unique link (with a $_GET). Any ideas how I can do this with PHP or Javascript (or both).
Pop-up script:
<!----- JAVASCRIPT FOR EACH ELEMENT ---->
<script type="application/javascript">
function openPopup<?php echo $persona->{'User ID'}; ?>() {
document.getElementById('<?php echo $persona->{'User ID'}; ?>').style.display = "block";
}
function closePopup<?php echo $persona->{'User ID'}; ?>() {
document.getElementById('<?php echo $persona->{'User ID'}; ?>').style.display = "none";
}
</script>
The pop-ups are created inside a foreach loop (PHP) with the onClicks in it.
Thanks in advance!
you can do like this:
<?php if (isset($_GET['my_get_var']) && !empty($_GET['my_get_var']) : ?>
<div class="my-popup">
<!-- my popup code -->
</div>
<?php endif; ?>
no need for js at all - just CSS, HTML and PHP

Including a common html header in all pages in website of 20 pages (with active class)

Assume I have 20 navbar items, each one linking to a different page on my website. And on each page those 20 items remain the same. To avoid copy-pasting across all .html files, other solutions have suggested doing this with php. But how would I make the active menu item lit white for example? I want to refrain from copy-pasting the header across to all the .html files, because if I want to add one more navbar item, I will have to manually add it to all .html files.
There must be a simple solution with an active item for the active page.
========EDIT========
Naomik, your javascript solution looks most promising, although I currently can't get it to work (see second edit below).
My navbar is defined in nav.html:
<nav id="nav" class="navbar navbar-inverse">
<div>
<ul id="navigation" class="nav navbar-nav navbar-left">
<li class="active"><a href="about.html" >About</a></li>
<li><a href="services.html" >Services</a></li>
<li><a href="pricing.html" >Pricing</a></li>
</ul>
</div>
</nav>
And this is one of the three html pages (about.html). I use JS to load in the nav.html file. The JS snippet before the closing body tag is the one provided by naomik.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$.get("nav.html", function(data){
$("#nav-placeholder").replaceWith(data);
});
</script>
</head>
<body>
<!-- *** NAVBAR *** -->
<div id="nav-placeholder"></div>
<!-- *** MAIN TEXT *** -->
<h1>ABOUT</h1>
<script>
function removeQueryString(url) {
return url.split('?')[0]
}
[].forEach.call(document.querySelectorAll('a'), function(elem) {
if (removeQueryString(elem.href) === removeQueryString(window.location.href))
elem.classList.add('is-active')
else
elem.classList.remove('is-active')
})
</script>
</body>
</html>
============EDIT==========
Although Naomik's solution leads to a flashing website on every load of a page. I have therefore applied Relisora's solution.
Thanks
You first want to give each of your 20 pages a name ( or a number ).
On each page, write the page name
<?php $page_name = "index" ?>
Then you import your navbar
<?php include 'navbar.php'; ?>
Now in your navbar.php you want to check on what $page_name you are
<?php if ($page_name == 'index') {echo ' id="active"';} ?>
And you do that for each page you have.
Now you'll just want to have #active {} in your CSS to determine the style, and your current page will show with active style.
Edit :
Now that we can write id="active", we want it to be in liso we can use the class :
<li<?php if ($page_name == 'index') {echo ' id="active"';} ?>>Home page</li>
Don't forget to add the link :
<li<?php if ($page_name == 'index') {echo ' id="active"';} ?>><a href="#" >Home page</a></li>
Don't do this this with PHP. You can add a little JavaScript to the end of your HTML before the closing </body> tag
Notice: Clicking the links in the snippet preview will not work for obvious reason. They are only there to show you that the correct link will highlight.
StackOverflow Code Snippets run from the URL http:stacksnippets.net/js. Knowing this, we can verify that our code works by making sure any href="/js" links get the is-active class.
After reading that notice above, click the Run code snippet button below
code {
font-family: monospace;
background-color: #ccc;
padding: 0.25rem;
}
.is-active {
background-color: blue;
color: white;
}
a {
display: inline-block;
padding: 0.25rem 0.5rem;
}
<h4>
This window is currently at url:<br>
<code>http://stacksnippets.net/js</code>
</h4>
js
html
php
<p>The <b>js</b> link above gets the is-active CSS class because it matches the window's current pathname</p>
<script>
[].forEach.call(document.querySelectorAll('a'), function(elem) {
if (elem.pathname === window.location.pathname)
elem.classList.add('is-active')
else
elem.classList.remove('is-active')
})
</script>
Notice that each a element in the original HTML does not have any class attribute. After the JS runs, notice that only the js link will automatically be given the is-active CSS class.
Here's a jQuery solution for you.
code {
font-family: monospace;
background-color: #ccc;
padding: 0.25rem;
}
.is-active {
background-color: blue;
color: white;
}
a {
display: inline-block;
padding: 0.25rem 0.5rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>
This window is currently at url:<br>
<code>http://stacksnippets.net/js</code>
</h4>
js
html
php
<p>The <b>js</b> link above gets the is-active CSS class because it matches the window's current pathname</p>
<script>
function highlightActiveLinks() {
$('a').filter(function(idx, elem) {
return elem.pathname === window.location.pathname
}).addClass('is-active')
}
highlightActiveLinks()
</script>
In yours, you will need this tho. This can't be demo'd in the SO snippet, sorry.
$.get('nav.html', function(data) {
// ...
highlightActiveLinks()
})
make a .html file with just the navbar and include it in an iframe
<iframe src="navbar.html"/>
Here is some sample php code that iterates through an array of paths and constructs a menu.
If the function is given an active path (current path) as an input it compares to each path and if they match it adds a class to the link.
I've hard coded an active path to demonstrate the output.
You can bundle all this up into a file called something like nav.php and include it on each page.
<?php
include 'includes/nav.php';
?>
nav.php:
<?php
$paths = array(
'/foo/',
'/foo/bar/',
'/foo/baz/',
);
function nav($paths, $active_path = null) {
$o = '';
foreach($paths as $path) {
$a_class = $active_path == $path ? 'active' : '';
$o .= "<a class='$a_class' href='$path'>$path</a><br />\n";
}
return $o;
}
$active_path = strtok($_SERVER["REQUEST_URI"], '?');
$active_path = '/foo/bar/';
?>
<?php echo nav($paths, $active_path); ?>
Output:
<a class='' href='/foo/'>/foo/</a><br />
<a class='active' href='/foo/bar/'>/foo/bar/</a><br />
<a class='' href='/foo/baz/'>/foo/baz/</a><br />
Personally however I prefer adding the active class with javascript. In which case you can just construct a html snippet and take advantage of the php include, server side include, or js include to add the html to each page.
for bootstrap
<a class="nav-link <?php if ($page_name == 'index') {echo "active";} ?> href="index.php">Home</a>
or in shorthand
<a class="nav-link <?php echo ($page_name == 'index') ? "active" : "";?> href="index.php">Home</a>
First of all rename the file name sample.html with sample.php
just use include syntax for php:
<?php include("sample.php"); ?>
or
<?php require("sample.php");?>
Add this in all 20 pages after remove the code.
Hope this will helps!
It can do by php.
First you create all pages as php files.
Create one file as nav_menu.php. In this page code all menu items.
In all pages instead menu codes include nav_menu.php
To give active class use$_SERVER["SCRIPT_NAME"] to check current url equals to particular url. If it is equal add class active.

HTML executes different php function onclick

I have the following problem. No matter which image I click, function 2 gets executed. Thanks a lot for your help.
<l href='<?php echo function1(); ?>' onclick='alert("ON!")'> <IMG STYLE="position:relative; margin-top: 40px" SRC="/img/on.png" page="control.php"></l>
<l href='<?php echo function2(); ?>' onclick='alert("OFF!")'> <IMG STYLE="position:relative; margin-top: 40px; margin-left: 80px" SRC="/img/off.png" page="control.php"></l>
The purpose of it is to execute different sql queries but they both execute the same query. The functions are included in a separate php. My only guess at the moment is that it is related to the styling.
The l> tag:
$( document ).on(
"click",
"l",
function( event ){
// Stop the default behavior of the browser, which
// is to change the URL of the page.
event.preventDefault();
// Manually change the location of the page to stay in
// "Standalone" mode and change the URL at the same time.
location.href = $( event.target ).attr( "page" );
}
);
As you haven't provided your php code yet here are my assumptions about your case:
function1() does some mysql query like that: UPDATE t SET state='on'...
function2() does almost the same: UPDATE t SET state='off'...
By using this code:
<?php echo function1(); ?>
<?php echo function2(); ?>'
You are basically calling both functions. First one switches something on then second one turns it off again and makes you think that only second query was executed. There is a problem with the logic of your code.
You can achieve your goal by using GET variables and running first or second function depending on its value. Here's example script
PHP:
<?php
if (isset($_GET['action'])) {
if ($_GET['action'] == "on") {
function1();
elseif ($_GET['action'] == "off") {
function2();
}
}
?>
HTML:
<span onclick="alert('ON!')"> <IMG STYLE="position:relative; margin-top: 40px" SRC="/img/on.png" page="control.php?action=on"></span>
<span onclick="alert('OFF!')"> <IMG STYLE="position:relative; margin-top: 40px; margin-left: 80px" SRC="/img/off.png" page="control.php?action=off"></span>

iframe doesn't getting hidden using JQuery

In my page I have a div with another div and an iframe as shown below.
<div class="v_dissc_tab" id="tabs-1">
<div id="publicevent">
<div class="crtraone" style="margin-left:800px;">
<button onclick="addpublic()">Add New</button>
</div>
<div>
<table width="100%">
<tr>
<td><b>Programme</b></td>
<td><b>Scheduled Start Time</b></td>
<td><b>Scheduled End Time</b></td>
<td><b>Amount</b></td>
<td><b>Status</b></td>
<td></td>
</tr>
<tr>
<?php if($publicnum>0)
{
}
else
{ ?>
<td colspan=6>
<?php echo "No any public channel programmes";?>
</td>
<?php }?>
</tr>
</table>
</div>
</div>
<iframe id="calendarframe" style="width: 100%;height:600px;display:none;" src="<?php echo base_url()?>index.php/channel/viewbookings">
</iframe>
</div>
On page loading, the div with id publicevent will be shown and the iframe is hidden. When I click on Add New button, the iframe will be loaded. Inside iframe I am loading another page which contains a button
<button onclick="managepublic()">Manage Public Events</button>
On clicking this button, I want to show the div with id publicevent and want to hide the iframe (as when the page is firstly loaded). Shown below is managepublic().
function managepublic()
{
location.reload(); // not making any changes
//$('#publicevent').show(); Tried with this also
//$('#calendarframe').hide();
}
Can anyone help me to solve this. Thanks in advance.
dont' use location.reload ,use only following code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
function managepublic()
{
$('#publicevent').show();
$('#calendarframe').hide();
}
On clicking this button, I want to show the div with id publicevent
and want to hide the iframe (as when the page is firstly loaded).
Check if this helps.
$('iframe').attr( "src", "http://www.apple.com/");
$('iframe').load(function() {
$('iframe').show()
$('#loaded').hide();
});
$('#button').click(function() {
$('#loaded').show();
$('iframe').hide();
});
JSFiddle
Try the following code snippet.
You are referring elements of <iframe>'s parent.
function managepublic(){
$('#calendarframe', window.parent.document).hide(250, function() {
$('#publicevent', window.parent.document).show();
});
}
Or
function managepublic(){
window.parent.$('#calendarframe').hide(250, function() {
window.parent.$('#publicevent').show();
});
}
Or Change the order of the hide events.
function managepublic(){
window.parent.$('#publicevent').show();
window.parent.$('#calendarframe').hide();
}
Note :
For this to work, parent must have jQuery included.
It won't work if parent is in different domain.

How to make checkbox visible when main checkbox checked?

good morning guys,
I have 3 checkboxes created in php. one that i want to use as a controller
<p>
<?php $creates = array('name'=> 'single_obs_value','class' => 'singleobsyes','value'=> '1','style'=>' float: left; margin-right: 2px;'); ?>
<?=form_label('Single Observation : ');?>
<?=form_checkbox($creates);?>
<br>
</p>
And the other two are brought in from a database array variable.
<p>
<?php foreach($obsnames as $cp){ ?>
<?php $create = array('name'=> 'cms_permissions[]','class' => 'singleobs','value'=> $cp->id,'style'=>' float: left; margin-right: 10px;'); ?>
<span style="width:200px; float:left">
<?=form_checkbox($create ).' '.form_label($cp->field_name);?>
</span>
<?php } ?>
</p>
How do i first make the two brought in by the database invisible when the page loads. Then when the controller checkbox is ticked make the two checkboxes visible again. If possible with a jquery function that uses the class of the controller checkbox as such.
$('#singleobsyes').change(function(){
Rather than
$('input[type="checkbox"']
As i use other checkboxes on the page and i believe that may cause some conflict.
try this
$(document).ready(function(){
$('input[type="checkbox"]').not('.singleobsyes').hide();// hide all checkboxes other than controller
$('.singleobsyes').change(function(){
if($(this).is(':checked')
$('input[type="checkbox"]').not('.singleobsyes').show();
else
$('input[type="checkbox"]').not('.singleobsyes').hide();
});
});
update: see this fiddle
you can also do this with css selectors as
html
<input type="checkbox" class="singleobsyes" name="a"/>check to show others
<input type="checkbox" class="singleobs" name="b"/>
<input type="checkbox" class="singleobs" name="c"/>
css
.singleobs{
display:none;
}
.singleobsyes:checked ~ .singleobs{
display:block !important;
}
fiddle
you can use wrapper too
fiddle v2
To make the checkboxes invisible you can style="display:none"
Now you can put on the "main" check box an onchange="showem();" attribute.
function showem()
{
$('#checkbox1id').toggle();
$('#checkbox2id').toggle();
}
EDIT: Changes show to toogle
You can make it simple this way,
$(document).ready(function(){
$('input[type="checkbox"]').not('.singleobsyes').hide();
$('.singleobsyes').on("change", function(){
$('input[type="checkbox"]').not('.singleobsyes').toggle();
});
});

Categories