Javascript - getElementByID - Error - javascript

I am getting this error message in my Javascript.
Unable to get property 'style' of undefined or null reference
document.getElementById('BS2').style.display='block';
What is going on it that sometimes the Element ID is not showing. Is there a way to check if the element is there then do this else, go to the next line of code?
function showb() {
if(document.getElementById('BS1').style.display=='none') {
document.getElementById('BS1').style.display='block';
document.getElementById('BS2').style.display='block';
document.getElementById('BS3').style.display='block';
document.getElementById('BS4').style.display='block';
}
return false;
}
Sometimes the BS1 is showing, BS3 is Showing and BS4... etc.

document.getElementById() returns an object just like anything else. You can assign it to a variable and check the null-ness of the variable:
var bs1 = document.getElementById('BS1');
if (bs1) {
.. do stuff if bs1 is present
} else {
.. do stuff if bs1 is not there
}

AS pointy said in his comment, you should chekc whether there is an element with the desired ID before trying to read its properties. You could use a piece of code like this:
var element = document.getElementById('BS2'); // or any other ID
if (element) { // if no element is found, this evaluates as a logical false.
element.style.display='block';
}
Getting the element in a variable also has the advantage that your code becomes more readable. And since you use this multiple times, you could create a function to encapsulate that logic. Good luck!

Well if the property style hasn't been modified it means that it is just ("")
function showb() {
if(document.getElementById('BS1').style.display) {
document.getElementById('BS1').style.display='block';
document.getElementById('BS2').style.display='block';
document.getElementById('BS3').style.display='block';
document.getElementById('BS4').style.display='block';
}
return false;
}
it is going to be solved just like that because ("") is a falsy value

Related

Class syntax cannot access variable properly in Javascript

I'm learning the class syntax in javascript. I'm trying to define a class, which holds a person's first and last name, tardies and absence count. The tardies and the absences are automatically set to 0 on instance initialization. Below is my code with a function that adds tardies and prints the amount of tarides:
class Student{
construtor(firstName,secondName){
this.firstName=firstName;
this.secondName=secondName;
this.tardies=0;
this.absences=0;
}
IncreaseTardies () {
this.tardies+=1
return this.tardies;
}
}
//Test
let Sample = new Student("A","B");
//Output undefined
Sample.IncreaseTardies()
//Output NaN
//Expected output 1
The code doesn't seem to work as intended since it returns NaN instead of the value+1 when IncreaseTardies() is called. I tried placing a console.log inside the constructor, which gave no result at all and adding breakpoints with identical success. What is the error in my code that prevents it from increasing the number of tardies?
The issue was a typo in the constructor function as a name. Thanks to jonrsharpe for pointing out the issue.
The working code is:
class Student{
constructor(firstName,secondName){
this.firstName=firstName;
this.secondName=secondName;
this.tardies=0;
this.absences=0;
}
IncreaseTardies () {
this.tardies+=1
return this.tardies;
}
}
Spelling of constructor is not correct, Please change it to constructor from construtor, Here c is missing... :)

Boolean in IF Condition causing Errors in JavaScript

I am developing a webpage with fairly simple JavaScript. My entire JavaScript code is:
function showUnlockPopup(isViolated,instId,unlock_done,unlock_total,period,endDate){
alert(isViolated);
if(isViolated){
if(unlock_done < unlock_total){
showInfoPopup(instId,unlock_done,unlock_total,period);
} else {
showNoUnlocksPopup(instId,unlock_done,unlock_total,period,endDate);
}
} else {
showNotViolatedModal();
}
}
However, irrespective of the value of the 'isViolated' variable, my 'showInfoPopup' function is called.
I have checked the code for the method call too:
<button onClick="showUnlockPopup(isViolated)">Unlock</button>
The alert shows 'true' or 'false' values correctly, but the logic runs for only 'true' irrespective of the value.
I think I am missing something fairly basic here. I tried a lot, but of no use. Kindly help me with the same.
it is because isViolated is returned as a string. so unless the string is null it will be true if it has some contents. You should change your check to isViolated == 'true', make a new variable that is a boolean and assign it depending on isViolated or something third.

If/elseif statements not working

For a reason I can't Identify, this isn't being successfully called, I've tried everything I can think of, but nothing seems to get this to work, it has no errors.
<img id="risk" src="assets/R0.png" width="100" height="150" style="border: dotted;"><br>
<button id="ContinueBtn" onclick="Continue()">Continue</button>
if (document.getElementById("risk").src == "assets/R0.png"){
document.getElementById("risk").src = "assets/R1.png";
}
else if (document.getElementById("risk").src == "assets/R1.png"){
document.getElementById("risk").src = "assets/R2.png";
}
else if (document.getElementById("risk").src == "assets/R2.png"){
document.getElementById("risk").src = "assets/RF.png";
document.getElementById("happiness").src = "assets/PF.png";
document.getElementById("main").src = "assets/fired.png";
alert("Debug")
var Cont = document.getElementById("ContinueBtn");
Cont.parentNode.removeChild(Cont);
}
When I add an else statement to it, it by passes the if and elseif's, making it seem like it is not finding anything for "risk",
else{
alert("An error has occured! Try refreshing your page.")
}
Short answer:
When you test the .src property in JS, some browsers report the full path of the image even when your original markup only specified a relative path. Which means your == comparison will fail.
Long answer:
Assuming that block of code is called after the elements have been created, I think you'll find that the problem is that the src you set in your html is not the same as what is reported when you test the .src property. If your source code sets a relative path for the src you may find the .src property value reported by the browser is actually the full path. So, e.g.:
<img src="assets/R0.png">
...and then:
console.log(document.getElementById("risk").src);
...will log "http://www.yourdomainhere.com/fullpath/assets/R0.png"
Which of course won't be equal when you compare with ==. Obviously you can easily test this by adding a console.log() statement just before the first if (or use an alert() if you must). Whenever you find an if statement isn't doing what you expect the first thing to try is adding a console.log() of the variables involved in the expression so that you can be sure they have the values you think they do.
If that is what's happening, then you obviously just need to use string functions to extract the last path of the path. E.g.:
var imgEl = document.getElementById("risk"),
imgSrc = imgEl.src.split("/").pop();
if (imgSrc == "R0.png"){
imgEl.src = "assets/R1.png";
} else if (imgSrc == "R1.png") {
imgEl.src = "assets/R2.png";
}
// etc.
The code imgEl.src.split("/").pop() that I've used takes the full path and uses .split() to create an array with all of the pieces between the forward slashes and then .pop() to take the last "piece", i.e. the last array element.
(I've also introduced a variable imgEl to reference your img element, because that's much neater and more efficient than repeatedly calling document.getElementById() for the same element.
Try using RegExp:
var risk = document.getElementById("risk");
if (risk.src.match("assets/R0.png")){
risk.src = "assets/R1.png";
} else if(condition) {
...
} else {
...
}

jQuery has conditional

Trying to write a conditional with jQuery that basically states, if div.gathering does not contain a.cat-link then do the following. I have tried the following but it doesn't seem to work. Can anyone shed some light on this?
if($("div.gathering:contains('a.cat-link')")){
$(".gathering").append("<a href='#"+data[i]["categories"][0]["category_id"]+"div' class='cat-link' id='"+data[i]["categories"][0]["category_id"]+"' rel='external'>"+data[i]["categories"][0]["category_name"]+"<br />");
}
How about this :
if($("div.gathering").find("a.cat-link").length == 0){
// Conditional statement returned TRUE
}
jQuery selectors return arrays of objects that matched the given selector. This is why we use the length property.
The method that you used - $("div.gathering:contains('a.cat-link')")
would return an empty array and when testing against any object that actually exists (even if it is an empty array) JavaScript will return true.
Example -
var nateArr = [];
if (nateArr){
// Do the dishes...
}else{
// Eat some waffles...
}
If you test this for yourself you will never stop washing those dishes because even though the nateArr contains zero elements it still exists therefore the conditional statement will always return true.
And your fingers will go all wrinkly
try this....
$("div.gathering:not(:contains(a.cat-link))")
.append("<a href='#"+data[i]["categories"][0]["category_id"]+"div' class='cat-link' id='"+data[i]["categories"][0]["category_id"]+"' rel='external'>"+data[i]["categories"][0]["category_name"]+"<br />")
this will only return the div with class gathering which does not have a.cat-link....
hope this helps....

Trying to get some jQuery functions to run in order. Is callback the issue?

I'm trying to do some things in order, and I'm having some trouble.
When the button with the id #sub_button is clicked,
Make sure each element with class ".verify" has it's own object value (see code)...
... if not, blur that element (will run some other code and create an object for it).
AFTER the above IF check is COMPLETE (now all elements should have an object), THEN run function "isitgood". (The "isitgood" function is running before all elements get their object values, which is done on blur)
$("#sub_button").click(function() {
$(".verify").each(function(){
objtitle = $(this).attr('id');
if (!myObj[objtitle]) {
$("#"+objtitle).blur(); // Define anything undefined
}
}); // end each
isitgood();
}); // end click function
function isitgood(){
if (myObj.login_id == "ok" && myObj.email == "ok") {
// submit the form
} else {
// shows error
}
}
Also, once I get this executing in the right order, it would be nice to do some sort of .each loop to check if all the object values == "ok" instead of specifying all of them in the function. All of the names of the objects (ie. login_id, email) are the ID attr of any element with class name .verify.
Well, you could do a quick index check in the click callback:
var sub_buttons = $("#sub_button");
sub_buttons.click(function() {
$(".verify").each(function(index){
objtitle = $(this).attr('id');
if (!myObj[objtitle]) {
$("#"+objtitle).blur(); // Define anything undefined
}
if (index == sub_buttons.length - 1)
isitgood();
}
}); // end each
}); // end click function
This will check if you're on the last element in the jQuery object, and if so, will run the isitgood() function. This way, you make sure that you're finished with the $.each method before executing isitgood()
Javascript is asynchronous. Your isitgood() will always fire while .each is still doing it's thing.
That said from your code it's not clear what you're trying to accomplish. The way you're using .each seems to indicate that you have multiple of the same ID attributes on your tags. That won't work, IDs have to be unique. Also you seem to be mixing jQuery and regular Javascript. Use one or the other. Actually just use jQuery, you'll save yourself time and effort!
If you do have unique ids then you shouldn't need the .each at all. Just check the appropriate ids with your if statement.
Please provide more of your code and i can update this with a better answer. For instance what does your myObj look like? How do elements of it get the value of ok? It doesn't seem to get set within your call to .each().

Categories

Resources