Can't find any div using document.getElementById - javascript

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 . "')";

Related

Set DIV visibility from a PHP variable [duplicate]

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>

Set javascript variable to the value of a button with different text

I have a button thats value is set based on a mysql query in php like so:
echo "<td><button class='jsontable' onclick='Copythat(this.value)' value='" . $row['json'] . "'> " . $row['name'] . "</button></td>";
the text of the button is the name row, which works currently.
and a function that i have basically in place to try and grab the string and send it to the load function. the load function needs to receive only text of that mysql row json
function Copythat(el.val) {
var jsontoload = $(el.val).html();
load(jsontoload);
}
If you pass this to your function, you get the context of the element where the event occurred. Once you've got that, you can pass it to jQuery and you can get the "value" attribute using the .val() shortcut method.
Note that function Copythat(el.val) { needs to be something simply like function Copythat(val) { - function parameters must be standalone variables, they cannot be written like object properties.
function Copythat(input) {
var attrValue = $(input).val();
alert(attrValue);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='jsontable' onclick='Copythat(this)' value='Something'>A button</button>
You could also convert the whole thing to jQuery and ditch the inline event handler:
$(function() {
$(".jsontable").click(function(event) {
var attrValue = $(this).val();
alert(attrValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='jsontable' value='Something'>A button</button>
Or it should also be noted that for something as simple as this you don't really need jQuery at all:
function Copythat(input) {
alert(input.value);
}
<button class='jsontable' onclick='Copythat(this)' value='Something'>A button</button>
Another further simplification if you literally only need the value to go into your function:
function Copythat(input) {
alert(input);
}
<button class='jsontable' onclick='Copythat(this.value)' value='Something'>A button</button>

Uncaught TypeError: Cannot read property 'style' of null concerning a script in an echo

I'm trying to change the color of a div on an onclick event.
Here is the error I'm getting:
Uncaught TypeError: Cannot read property 'style' of null
Here is the code:
function changeSelection (newClick) {
document.getElementById(newClick).style.backgroundColor="#4bc970";
document.getElementById(newClick).style.color="#FFFFFF";
if(oldClick!="" && document.getElementById(oldClick)!=null && oldClick != newClick){
document.getElementById(oldClick).style.backgroundColor="#d2d2d2";
document.getElementById(oldClick).style.color="#332836";
}
oldClick = newClick;
}
The echo is found on another php page.
echo ("<tr><td><div class='courseDiv' onclick=changeSelection(".$classID.");><p class='textInsideLeftTable'>".$className. "</p><p class='arrow'>></p></div></td></tr>");
Any input will be appreciated.
More Code :
<?php
require("connect.php");
session_start();
$stmt = $db->prepare('SELECT * FROM users INNER JOIN studentparent ON users.parentID = studentparent.parentID INNER JOIN studentsclasses ON studentparent.studentID = studentsclasses.studentID INNER JOIN classes ON classes.classID = studentsclasses.classID WHERE users.parentID=:parentID');
$stmt->execute(array(
':parentID' => $_SESSION['parentID']
)) or die(var_dump($stmt->errorInfo()));
$result = $stmt->fetchAll();
foreach ($result as $row) {
$className = $row['classCode'];
$classID = $row['classID'];
echo ("<tr><td><div class='courseDiv' onclick=\"changeSelection('".$classID."');\"><p class='textInsideLeftTable'>".$className. "</p><p class='arrow'>></p></div></td></tr>");
}
?>
ANSWER :
I inversed the "" with ''. Also, I forgot to give it the div id. I was trying to change the value and not the div value.
I hope it makes sens.
echo ('<tr><td><div id="div_'. $classID .'"onclick="changeSelection(\'div_'.$classID.'\');" class="courseDiv"><p class="textInsideLeftTable">'.$className. '</p><p class="arrow">></p></div></td></tr>');
You need to add single quotes around it, so that JavaScript will treat it as a string instead of a variable.
changeSelection('".$classID."')
document.getElementById(newClick) gives you null means that the id passed as newClick doesn't exists or it is not found in the current context.
add statement console.log(newClick); to your changeSelection() on the first line. And check console(F12 developer tools) to see whats the value being passed.
So My knowledge of PHP is pretty limited but as far as i remember, shouldn't you use
changeSelection('"$classID"')
instead of
changeSelection('".$classID."')
why are there two dots before and after the $classId, if you have stored Id of your div tag, in a variable called classId all you need is $classId to get its value and document.getElementById("classId_value") should return you the element.

JAVASCRIPT : Parameter Passed Is "Not Defined"

I'm creating a page that should read data from the database, display it as a table, and allow row-wise editing of the entries (using AJAX calls). Here are brief code snippets where the problem comes -
Javascript:
function editParam(bname, button) {
alert(bname); //this part doesn't happen, the error on console comes up before it
tr = button.parentNode;
while (tr && tr.nodeName.toUpperCase() !== "TR" && tr.nodeName.toUpperCase() !== "BODY") {
tr = tr.parentNode;
}
if (!tr || tr.nodeName.toUpperCase() !== "TR") {
return;
}
//some more code
}
PHP:
//get $row_users['Name']
while ($row_users = mysqli_fetch_array($results)) {
echo "<form method='POST'> //some <tr><td></td></tr>
<button onclick='editParam(".$row_users['Name'].", this)'>Edit</button>
</form>";
}
My data in the column Name is like "B1", "C2", etc.
Error onclick of button : B1 is not defined.
While running the code for other text or numbers, it worked fine. So I understand that my problem has to do with the datatype. However, I do not know how resolve the same.
Any suggestions would be much appreciated, thanks!
You need to add quotes around $row_users['Name'] since otherwise it is interpreted as a JS variable.
"<button onclick='editParam(\"" . $row_users['Name'] . "\", this)'>Edit</button>";

jQuery $.post() using output data as selector

I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr

Categories