Set DIV visibility from a PHP variable [duplicate] - javascript

This question already has answers here:
Hiding a Div using php
(6 answers)
Closed 1 year ago.
I want to show and hide a div based on a condition. This time I am not using any function since I thought it would be better as simple as possible.
I am trying to show and hide 2 DIVs based on a "status" of the user ($new). I don't know if it's possible to assign a PHP value to a JavaScript variable and the best way to do it ...
"var" is supposed to get the value of "$new".
Javascript:
<script>
var var = $new;
if (var != 1) {
document.getElementById("subjectr").style.display = "block";
} else {
document.getElementById("subjectr").style.display = "none";
}
</script>
HTML:
<center>
<div id="subjectr" value="<?php echo "$new"?>" style="display: none">
COORDINADOR
</div>
</center>
If you know a better way to do it, I would appreciate your help.

You don't need JS, simply echo or wrap the desired HTML into an if $new is true right on the server-side
Using PHP
<?php if ($new) { ?>
<div>Content for new users</div>
<?php } ?>
Using CSS (and PHP)
<div class="<?= $new ? '' : 'isHidden' ?>">Content for new users</div>
.isHidden { display: none; } /* Add this class to CSS file */
The above might come handy if at some point, by using JavaScript you want to toggle the visibility of such element using .classList.toggle('isHidden') or jQuery's .toggleClass('isHidden')
Using JavaScript (and PHP)
If you really want to pass your PHP variable to JavaScript:
<div id="subjectr">Content for new users</div>
<script>
var isNew = <?php echo json_encode($new); ?>;
document.getElementById("subjectr").style.display = isNew ? "block" : "none";
</script>
<!-- The above goes right before the closing </body> tag. -->
PS:
The <center> tag might work in some browsers but it's long time obsolete. Use CSS instead.
The value is an invalid HTML5 attribute for div Element. Use data-value instead.
What's doing the method=POST; on an <a> tag?
var var is a syntax Error in JavaScript, var being a reserved word. Use a more descriptive var isNew instead.

Instead of using javascript, you could use PHP to influence the display style of your div by using a ternary to decide whether it is none or block:
<center>
<div id="subjectr" value="<?=$new?>" style="display: <?=$new != 1 ? 'block' : 'none'?>">
COORDINADOR
</div>
</center>

For first, you should avoid to use var as a variable in your JS code, since it's an reserved key.
For your problem, revise your JS code:
<script>
var cond = document.getElementById('subjectr').getAttribute('value');
if (cond != 1) {
document.getElementById("subjectr").style.display = "block";
}
else {
document.getElementById("subjectr").style.display = "none";
}
</script>
You can get attribute result using getAttribute method in javascript, or attr method in jQuery.

A javascript variable can get the value of a PHP variable like so (assuming the PHP var is an integer):
var myvar = <?=$new?>;

Since you tag this as a PHP and a CSS issue, I think our mobile function is pretty near. This is our CSS "shownot" class:
.shownot { display: none !important; }
After, we use to hide certain cols on device mobiles, in your case the "$new" var:
<?php
$new = isMobile() ? 'shownot' : '' ;
?>
Finally, use as class whenever you need
<div id="subjectr" class="<?php echo $new;?>">
COORDINADOR
</div>

Related

Passing a variable into a javascript function in PHP to make specific divs hide or show?

I am trying to create a simple FAQ page where the user clicks the question and the answer appears below it (or hides it, if clicked again).
I got it working up to a point where all the questions will show the answer labeled "ans1". But I would like to pass a variable from each question into the function so it makes the associated answer appear. Question 1 will show Answer 1, Question 2 -> Answer 2, and so on.
My function...
function theAnswer() {
var x = document.getElementById("ans1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
PHP...
<?php
$answer = 1;
foreach($faqArray as $faq) {
?>
<div class='product_container'>
<div class='product_cell'>
<a onclick="theAnswer()" href='#'>
<?php echo $faq[0];?>
</a>
</div>
</div>
<div class="answer" id="ans<?php echo $answer;?>" style="display:none;">
<p><?php echo $faq[1];?></p>
</div>
<?php
$answer = $answer + 1;
} ?>
If I put a variable in the onclick="theAnswer()" that dictates the associated div, how can I get the function to perform the desired result?
Thanks!
Your PHP code is run server-side and your Javascript code is run client-side. So the two codes cant interact with each other. I recommend hiding your element with CSS use something like this:
.hide{
display : none
}
and set your your div to hide like this
<div class='hide' id='answer-<?php echo $answer;?>'> .... </div>
and you would remove hide from your element's class list like this
function theAnswer(num){
answer = document.querySelector('#answer-' + num)
answer.classList.remove('hide')
}
in your php code youd have to put in the value
.....
<a onclick="theAnswer('<?php echo $answer;?>')" href='#'>
.....

Can't find any div using document.getElementById

I have a weird problem with my code, I'm changing the background color of some divs using Javascript, but "document.getElementById" is not finding the div and returns NULL.
Javascript:
function colorFill(id)
{
console.log(id); // Shows the correct string (r1h1)
var divID = document.getElementById(id);
// Even if I replace the id by "r1h1", directly the name of the div, it shows NULL
console.log(divID); // Shows NULL
}
The "id" is a string coming from a php function, that works, because when I try do alert(id), it shows up correctly (r1h1), but when I try to find the div using that "id", it returns a NULL. Also, I've tried to find other divs and it does the same.
Here's the div:
HTML:
<?php
include 'models/ms_model.php';
if (isset( $_SESSION['gameState'] ) && !empty( $_SESSION['gameState'] ))
{
fillGameTable();
}
?>
<div id="row1" class="Row rowActive">
<div id="r1h1" class="hole" style="float:left"></div>
</div>
I'm calling the Javascript function here:
PHP:
function fillGameTable()
{
echo '<script src="views/js/ms.js"></script>';
foreach($_SESSION['gameState'] as $ID)
{
echo'<script>colorFill("'.(string)$ID.'");</script>';
}
}
The weirdest this is that I have another function finding that same div and it works, something is wrong with this function ...
You are outputting the colorFill() function before the divs in the document. You either have to switch that order, to make sure that the elements are all in place in the document before you call the colorFill() JS function, like this:
<div id="row1" class="Row rowActive">
<div id="r1h1" class="hole" style="float:left"></div>
</div>
<?php
include 'models/ms_model.php';
if (isset( $_SESSION['gameState'] ) && !empty( $_SESSION['gameState'] )){ fillGameTable(); }
?>
Another option would be to refactor your code so that the fillGameTable() PHP function returns a javascript which is executed in the document ready event.
If you are calling the JavaScript function from PHP make sure you're quoting the argument for the function properly:
function colorFill(id)
{
var divID = document.getElementById(id);
console.log(divID);
}
colorFill(r1h1); // not a string, returns null
colorFill('r1h1'); // string, returns object
It is likely you have something like this in PHP:
echo "colorFill(" . $variable . ")";
What you need is this (note the inclusion of the quotes surrounding the argument):
echo "colorFill('" . $variable . "')";

Convert PHP objects array to javascript array

I retrieve image paths with the function get_all();. This get_all function retrieves images as an object. This object has the attributes name, source_path and date. I want my javascript to add images to a div. I have the following:
The instantiate.php includes files like Jquery and another JS file.
<?php
require_once("../../include/instantiate.php");
$photos = Photos::get_all();
$JSPhotos;
foreach($photos as $photo) { $JSPhotos + $photo->source_path; }
?>
<script type="text/javascript">
$(document).ready(function() {
var photos = <?php echo json_encode($JSPhotos); ?>;
for(var i = 0; i <= 10; i++)
{
create_image("../"+photos[i]);
}
});
This does not work. Anyone got a solution?
Solution in Jeroen's Post!
New Problem;
In the create_image function I set the class and src of the image element. When you click such an image I want an alert box to show up. I have checked if the class is set correctly, and I concluded that all images did have the classname "imgid". So, any idea why this dont work?
Script in the javascript part:
$(".imgid").click(function() {
alert("hey");
});
You are not assigning anything to your variable.
You probably want:
$JSPhotos = array();
foreach($photos as $photo) {
$JSPhotos[] = $photo->source_path;
}
Or something similar.

Whats wrong with my jquery select

login_view.php
I am just trying to use some jQuery to select the a drop down I have created via code igniter's form helper. I have tried different javascript statements on the browser console but keep getting "undefined" for this form element. :(
<?php
//build html for company drop down
$form_options['--'] = "--";f
foreach ($client_list as $client) {
$form_options[$client['co_id']] = $client['co_name'];
}
$js = 'id="companies"';
echo form_dropdown('', $form_options,'', $js);
?>
<input id="login" type="submit" value="Login">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">
$('#login').click(function() {
var co_id = $(this).find('#companies').val();
console.log(co_id);
});
</script>
In this case there is not need to use find() because the element companies doesn't have #login as its parent. So you need to change it too
var co_id = $('#companies').val();
Just use
var co_id = $('#companies').val();
$(this).find('#companies').val(); you are trying to find element with id companies inside element with id login which doesn't exists .
Id's are unique so can call them directly using id-selector

passing javascript variable in document.getElementbyID

I know this is a silly question but i am not able to get the required result.I want to assign a javascript variable bck in document.getElementById(bck) .Everything is working fine i.e. alert displaying the correct value of variable bck but when i am using it inside the document.getElementbyID i am getting the following error:
document.getElementById(bck) is null
I googled it and looked in SO relevant topics also but got nothing helpful.
the value of backdropcontent[m][1] is Reden,also the value of selectedbg is Reden.
<script>
for ( var m=0;m<backdropcontent.length;m++) {
if(selectedbg==backdropcontent[m][1]){
var bck=backdropcontent[m][1]+'div1';
alert(bck);
document.getElementById(bck).style.display = "block";
document.getElementById(bck).style.top = "0px";
}
}
</script>
html part:
<div class="mcdropdown" id="Redendiv1" style="display:none;position:relative">
<a style="cursor: default !important">
<input type="text" name="reden1" id="reden1" style="background-image: url('<?php echo $mosConfig_live_site; ?>/templates/performitor/images/123.png');background-repeat: no-repeat;height:14px;width:130px !important;color:#BDBDBD;border: 1px solid #8e9daa;" disabled="disabled" value="Totaal" autocomplete="off"/>
</a>
</div>
please note that i dont want to alter the structure of my code so please dont suggest any major change.
Any help will be appreciated.Thanks.
The element with id backdropcontent[m][1]+'div1', does not exist
It's throwing error mostly because your element doesn't exist on the page yet. Move your <script> block below your code or use window.onload event.
window.onload = function(){
//your code
}
Or using jquery:
$(document).ready(function() {
// your code
});
you use the code in the following pattern
<script>
for ( var m=0;m<backdropcontent.length;m++) {
if(selectedbg==backdropcontent[m][1]){
var bck=backdropcontent[m][1]+'div1';
alert(bck);
document.getElementById("bck");.style.display = "block";
document.getElementById(bck).style.top = "0px";
}
}
</script>
May be this code helps you.

Categories