I have a few hidden divs on page like this
<div class="form" id="scheduler" style="display: none;">
<div class="form" id="test" style="display: none;">
<div class="form" id="super" style="display: none;">
I would like a jscript which can be called to show these hidden divs based on criteria like this
<?php
if ($_GET['id'] == 'scheduler') {
call jscript function (show div id:scheduler in this case)
}
else if ($_GET['id'] == 'test') {
call jscript function (show div id:test in this case)
}
else if ($_GET['id'] == 'super') {
call jscript function (show div id:super in this case)
}
?>
thanks.
you cannot call javascript function from PHP, PHP is server side based and stands for Preprocesing Hypertext while Javascript is browser based.
You could use:
<?php
if ($_GET['id'] == 'scheduler') {
$showdiv = 'scheduler';
}
else if ($_GET['id'] == 'test') {
$showdiv = 'test';
}
else if ($_GET['id'] == 'super') {
$showdiv = 'super';
}
echo "<script type=\"text/javascript\">document.getElementById('".$showdiv."').style.display = 'block';</script>";
?>
but that should be at bottom of the page, after those divs are loaded.
<script type='text/javascript'>
function showDivById(id){
document.getElementById(id).visible = true;
}
<?php
$divs = array('scheduler','test','super');
if (array_seach($_GET['id'], $divs)!==false)
echo "showDivById({$_GET['id']})";
?>
</script>
Note that php code is within the <script>
Why don't you write your function to accept the id param of the query string?
<script>thefunction($get);</script>
This way you can save on if logic, and develop a more abstract function. It's less code, and easier to manage.
First of all. I would use jquery to show/hide divs...
but my concept would be a bit different then above,
<?php
if($_GET['id']){
echo '<script type="text/javascript">$(\'#'.$_GET['id'].'\').show();</script>';
}
?>
Hope that you got my idea, it's clean and pretty dynamic :)
Even though you've accepted an answer, another option would be to use only JavaScript with the aid of some JS to easily retrieve values from the query string.
function $get(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
}
var qs_id = $get('id');
if (['scheduler', 'test', 'super'].indexOf(qs_id) >= 0) {
document.getElementById(qs_id).style.display = 'block';
}
Demo: jsfiddle.net/Marcel/L69xt/show
Related
I have a page that receives incoming values from $_POST. One such value is from a drop down selector that allowed the user to select values 0 -10. I want to trigger a JQuery function if a value greater than 0 was selected.
So, if $_POST['DropDownSelection'] > 0, then my JQuery function should run.
How do I trigger the function?
If the function needs to be called in the original page then you can do this -
$('select[name="DropDownSelection"]').change(function() {
var newValue = $(this).val();
if(newValue > 0) {
// your function here
}
});
You don't need PHP, you just need to see if the value changed and then if the value is greater than 0.
If the function is in the page that gets posted to then you could do this -
<script>
var DropDownSelection = <?php echo $_POST['DropDownSelection']; ?>;
if(DropDownSelection > 0) {
// call your function here
}
</script>
Something i like to do for passing a PHP var to Javascript is to put in in an hidden input like that :
<input id="myValue" type="hidden" value="<?= $_POST['DropDownSelection']; ?>" />
The in your javascript :
if(document.getElementById('myValue').value > 0) //Do something
Depends on how your PHP code is connected to the HTML output. In the simplest case where PHP and HTML are in the same file, you could do something like
<? if ($_POST['DropDownSelection'] > 0) { ?>
<script>$.myFunction(...);</script>
<? } ?>
You can do like that.
var x = <?php echo $_POST['DropDownSelection'] ?>;
if(x>0){
jqueryFunction(); // your function call.
}else{
// whatever else you want.
}
Maybe this is oversimplified and a little hacky, but I don't see why this wouldn't work...
<script type="text/javascript">
function overZero() {
// do stuff...
}
<?php
if ($_POST['DropDownSelection']>0) echo('overZero();');
?>
</script>
$(document).ready(function(){
$("#dropdown-id").change(function(){
//check if the value is > 0 and then
// trigger your jquery function()
})
})
However, I want to also call that function when the user lands on the page with
a particular $_POST value for a field
There are 2 easy ways of doing this:
Make global funciton:
ex:
function print(){
alert('hello')
}
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>print()</script>";
}
?>
Or use triger function from jquery:
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>$('#dropdown').trigger('change');</script>";// execute the onchange event(function) attached to the dropdown
}
?>
First of all I appreciate that all members are trying to help each other.
I want div content by id in my javascript function. I've got function and it works fine with one div and it's content. But now I've got multiple records from DB, so to make div unique I have done following. where $i=$i+1 in while loop
<div id="<?php echo 'fvd'.$i; ?>" class="fake-checkbox star-checkbox"><a id="<?php echo 'tvd'.$i; ?>" onclick="respuestas('<?php echo $user_id1;?>'); return false;" href="#">Add to favourites</a></div>
so here I generate fvd1, tvd1 for next record fvd2,tv2 and so on
Below function process user id and get response by Ajax call and change caption from Add to favourites to Added to favourites and add class name 'checked' which change text color.
function respuestas(str) {
var popID = str;
var gett = document.getElementById('tvd1').innerHTML;
if (gett == 'Add to favourites') {
$.post('personals/addfavourite.php', {
ref: popID
}, function (data) {
if (data == 'no') {
alert('Sorry! something gone wrong!')
} else if (data == 'yes') {
var d = document.getElementById("fvd1");
d.className = d.className + " checked";
document.getElementById('tvd1').innerHTML = 'Added to favourites';
}
});
}
}
Now how can I parse fvd2,tvd2 and so on in this function.
Any help will be much appreciated..Thanks
If you add your $i to the function parameters you can get each grouping dynamically
onclick="respuestas('<?php echo $user_id1;?>',<?php echo $i;?>); return false;"
and
function respuestas(str,num) {
...
var gett = document.getElementById('tvd'+num).innerHTML;
...
var d = document.getElementById("fvd"+num);
...
document.getElementById('tvd'+num).innerHTML = 'Added to favourites';
...
}
You can do
onclick="respuestas(this, '<?php echo $user_id1;?>');
and the first param would be the <a> so you can do
function respuestas(elm, str) {
elm.getAttribute("id");
}
or so. (Not sure about the DOM method name)
BTW why don't you just put the $i to the call as well? Or maybe I didn't get the question right? If not, pls explain.
If you need to access the elements, well then you already have the <a> in elm, and the <div> is in elm.parentElement.
Check HTML DOM methods: https://developer.mozilla.org/en-US/docs/Web/API/Node.parentElement
I am running the javascript function shoh() below on page load to hide div's. This works fine on html hard coded divs but appears not to be working on divs that are created via php. Am I correct in assuming that the javascript runs first before the php creates the divs and that is why they aren't being hidden? If so, is there any other way to hide these divs after they are created? They need to be shown by default in case javascript is disabled?
code which runs with onload:
<script type="text/javascript">
function closeAllDivs() {
shoh('g1');
shoh('g2');
shoh('g3');
shoh('g4');
}
</script>
<BODY onLoad="closeAllDivs();">
javascript to hide divs:
function shoh(id) {
if (document.getElementById) { // DOM3 = IE5, NS6
if (document.getElementById(id).style.display == "none"){
document.getElementById(id).style.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.getElementById(id).style.display = 'none';
}
} else {
if (document.layers) {
if (document.id.display == "none"){
document.id.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.id.display = 'none';
}
} else {
if (document.all.id.style.visibility == "none"){
document.all.id.style.display = 'block';
} else {
filter(("img"+id),'imgout');
document.all.id.style.display = 'none';
}
}
}
}
php code which creates divs:
for ($i=0; $i < count($this->items); $i++){
<div style="display: block;" id="g<? echo $i ?>">
... code that displays items
</div>
}
It shouldn't really matter so much whether the php made the divs or whether they're hardcoded - by the time the HTML hits the browser, it's already the same thing. The server processes the PHP - by the time it leaves the server and heads to the browser, there is no PHP anymore.
I'd recommend using window.onload instead of a <body onload="">
window.onload = function() {
closeAllDivs();
};
Thanks to Wolfman Joe for letting me know the problem was likely not with the order of things. This told me the shoh() function was likely failing and therefore interrupting execution... so the code to close the divs was never executed. The solution was to build a check into the shoh() function to first make sure the div existed before attempting to change its property. As it turns out, not all divs $i were being created.
function shoh(id) {
if (document.getElementById) { // DOM3 = IE5, NS6
if (document.getElementById(id)){
if (document.getElementById(id).style.display == "none"){
document.getElementById(id).style.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.getElementById(id).style.display = 'none';
}
}
}
}
I have been looking all over for a way to do this.
I use a PHP while loop to get some variables from a database:
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<script type="text/javascript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
//-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
<? } //end while
?>
Sometimes i get 10 results, and i make 10 Go! bottoms. But when i come to the delete page, the $is variable is off cause the same as the last result, no matter witch of the bottoms i press..
Any ideas on how to get around that, so i get the confirm box, and still keep the right id to be deleted?
You're creating a global function called "go_there" for each entry, so only the last one will remain. Instead of that, create just one function, and fetch the "id" value from an attribute on the button.
function go_there(button)
{
var id= button.getAttribute("data-id");
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
}
Then:
<INPUT TYPE="button" value="Go!" onClick="go_there(this)" data-id="<?php echo $id ?>">
It seems to me like you're creating your javascript function in your loop as well so it only fires one of them (you're creating multiple functions with the same name. How is it supposed to know which one to use). You should create 1 javascript function and pass the id into it as a a parameter
<script type="text/javascript">
function go_there(id)
{
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
</SCRIPT>
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
echo '<td><form><INPUT TYPE="button" value="Go!" onClick="go_there(<?php echo $id; ?>)"></form></td></tr>'
} //end while
?>
Overall this is a poor way to do this. You should avoid wrtiting handlers inline unless you have a specific case where it is the only way. Much better if you attach a handler to the elements in questions (working fiddle - for firefox anyhow...):
<!-- output our inputs with the id value in an attribute data-id-value -->
<?php while ($row = mysql_fetch_array($query)): $id = $row["ID"]; ?>
<td><form><INPUT class="go-button" TYPE="button" value="Go!" data-id-value="<?php echo $id ?>"></form></td></tr>
<?php endwhile; ?>
<script type="text/javascript">
var goButtons = document.querySelectorAll('input.go-button'), // select all out buttons
// define our handler function
goThere = function (event) {
// get the id the we encoded from php from our data attr
var id = event.target.getAttribute('data-id-value');
if(confirm('Are you sure you want to delete?')) {
// if confirm is true then redirect to the delete url
window.location = "index.php?p=delete&id=" + id;
}
};
// loop over the buttons and attach the handler
for (var i = 0; i < goButtons.length; i++) {
goButtons[i].addEventListener('click', goThere);
}
</script>
The issue here is that that isnt necessarily cross browser. Thats typically one of the reasons people use libraries like jQuery or similar so that they don't have to normalize dom querying and listener attachment.
Here is a corrected script.
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<SCRIPT language="JavaScript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to == true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
Your button will not work because you have added the comment markers <!-- and --> to the function. If you want help with that then please comment.
Also, can you clarify you're issue in the comments? We can help you better then.
I want to toggle divs by clicking on links. but things are not going well for me when I click on a link it shows a new div but don hide the previous one
JavaScript Code
<script type="text/javascript">
function toggle(id){
var el = document.getElementById(id);
if(el != null && el.style["display"]== 'none'){
el.style["display"] = "block";
}
}
</script>
My divs code
<?php foreach($titles_data as $title){ ?>
<div style="display:none" id="content_<?php echo $title['idtitles'] ?>">
<div id="left-ad"></div>
</div>
<?php } ?>
My links code
<?php foreach($titles_data as $title){ ?>
<li class="flag_<?php echo strtoupper($title['language']) ?>">
<a id="title_<?php echo $title['idtitles'] ?>" href="" title="<?php echo $title['title'] ?>" onclick="toggle('content_<?php echo $title['idtitles'] ?>')">
</a>
</li>
<?php } ?>
How can it be done so that when i click on link its respective iv becomes visible and the previous one hides?
Thanks
Using native JS:
function toggle(id){
var el = document.getElementById(id);
el.style.display = el.style.display == "none" ? "block" : "none";
}
toggle("myId");
Using jQuery:
function toggle(selector) {
$(selector).toggle();
}
toggle("#myId");
To toggle the display, you dont need to do that much
$("#elementid").toggle();
In reference to your question
$('a').click(function() { // however this is select all anchors, better use class
// selector like $(".mylinkclass")
var id= $(this).attr('id'); //get the id
var ids = id.splite("_"); //split the id on "_", to extract the idtitles
$("#content_"+ids[0]).toggle(); // use that to toggle
});
Assuming that there is always only one div that is displayed, you can check for it:
Alter your logic, to declare a global variable to hold the value of the currently visible div. And then update that variable whenever a link is clicked, to hold the id of the currently visible div. So, using your exisitng code, you can do this :
using core javascript:
var visibleDiv;
function toggle(id){
// hide the previous div using visibleDiv
if(document.getElementById(visibleDiv)!= null) document.getElementById(visibleDiv).style["display"] = "none";
var el = document.getElementById(id);
if ( el.style["display"] == "" || el.style["display"] == 'none' ){
el.style["display"] = 'block';
}
visibleDiv = id; // update the current visible div name
}
using jquery like this :
var visibleDiv;
$("[id^=content_]").each(function() {
if($(this).is(':visible')){
visibleDiv = $(this).attr('id');
}
});
Check my new answer. I just created the sample html page, with 3 divs. Initially all are shown. When you click on one of them, it is hidden. When you click on some other div. The old one is made visible again and the current one is hidden. Modify the logic as per your requirements.
<html>
<head>
<title>asdsa</title>
<script type="text/javascript">
var visibleDiv;
function toggled(id){
//$('#div_2').html($('#div_1').html());
if(document.getElementById(visibleDiv) != null){ document.getElementById(visibleDiv).style["display"] = "block";}
var el = document.getElementById(id);
document.getElementById(id).style["display"] = "none";
visibleDiv = id;
}
</script>
</head>
<body>
<div id="div_1" onclick="toggled('div_1')">div1</div>
<div id="div_2" onclick="toggled('div_2')">div2</div>
<div id="div_3" onclick="toggled('div_3')">div3</div>
<hr/>
</body>
</html>
Thanks.