javascript if condition is not working - javascript

i'm trying to work the following code of script. but its not working. i don't know what is the problem. the x variable i created contains nothing. but still the if condition is not working. i have tried printing the x variable in an alert box and it prints nothing, which means that it contains nothing. But in its not picking up the condition don't know why. And there are no console errors.
<div id="test">
</div>
<script>
var x = document.getElementById("test").innerHTML;
if(x == '') {
document.getElementById("test").innerHTML = 'There are No friends posts yet my love!!';
}
</script>

Your variable x contains not empty string but some spaces. Try to use trim() function to remove these symbols:
if(x.trim() == ''){
...
}

This will work!
<script>
var x=document.getElementById("test").innerHTML;
if(x.trim() == ''){
document.getElementById("test").innerHTML='There are No friends posts yet my love!!';
}
</script>

use innerText
if(x.innerText === ''){
https://jsfiddle.net/s4aLcfm5/

The issue is that your 'x' variable is not empty. It contains two return characters. Try removing all the white-space between your open and close div statement. Here is the corrected code:
<div id="test"></div>
<script>
var x=document.getElementById("test").innerHTML;
debugger;
if(x == ''){
document.getElementById("test").innerHTML='There are No friends posts yet my love!!';
}
</script>`
Simply add or remove returns within the div statement to see this work or not work.

Your code works. It all comes down to the way that your html is written:
<div id="test">
// This is an unnecessary space that's what is making your condition fail
</div>
<script>
var x=document.getElementById("test").innerHTML;
if(x == ''){
document.getElementById("test").innerHTML='There are No friends posts yet my
love!!';
}
</script>
Clean up your html: <div id="test"></div>
And you don't need anything else

Related

How to swap contents of header tag - HTML/Javascript

I have the following:
function changeFirst() {
let p = document.getElementById("firstElement")[0].innerhtml;
alert(p);
if (p = "<h1>This is the 1st element</h1>") {
document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>"
} else {
document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>"
}
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button onclick="changeFirst()">Change first element</button>
I basically want the button to alternate the contents of the firstElement div. Why doesn't this work?
Thank you
document.getElementById returns ONE element
Also = is assignment, you want == or === for comparison
Could you possibly mean this:
function changeFirst() {
let h = document.querySelector("#firstElement h1");
h.textContent = h.textContent==="This is the 1st element" ? "Changed first" : "This is the 1st element"
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button type="button" onclick="changeFirst()">Change first element</button>
Here is exactly what you asked for. You were close.
1) when including javascript, you can just use script tags and it will work fine, when you use JSON or JQuery, that's when you have to use an include tag of a .js file. javascript code can be notated with script type = text/javascript.
2) when making a comparison in javascript: use three equal signs (===)
when making a non variable type-sensitive comparison: use two equal signs (==)
when setting a variable: use one equal sign (=)
https://www.geeksforgeeks.org/difference-between-and-operator-in-javascript/
3) When calling dynamic header, it is not an array, so you don't need [0], you are just comparing the innerhtml of the dynamic header div and it is only one header, arrays are for multiple things. Keep working on code, as you seem to have a good start, and made some minor syntax errors.
<!DOCTYPE html>
<html>
<body>
<button onclick="changeHeader()">Click me</button>
<div id="dynamicHeader"><h1>Hello World</h1></div>
<p>Clicking the button changes the header.</p>
<script>
function changeHeader() {
if (document.getElementById("dynamicHeader").innerHTML === "<h1>Hello World</h1>") {
document.getElementById("dynamicHeader").innerHTML = "<h1>Goodbye World</h1>";
} else {
document.getElementById("dynamicHeader").innerHTML = "<h1>Hello World</h1>"
}
}
</script>
</body>
</html>
Try like this. Here I introduced a flag and switched it to check content.
var changed = false;
function changeFirst() {
if (!changed) {
changed = true;
document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>";
} else {
changed = false;
document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>";
}
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button onclick="changeFirst()">Change first element</button>

Get value inside Div Javascript

ho,
I have a div that I access like so:
var gridcellrowvalue0 = gridcell0.innerHTML;
This returns to me the following div:
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
In my JS I would like to accesss the "DefaultText" variable and I have tried this:
gridcellrowvalue0.innerHTML;
gridcellrowvalue0.getAttribute("data-originaltext");
But none of them work. I'm assuming that getAttribute doesn't work because it is not really an element, it's innerhtml.
My goal is to use the "DefaultText" value in an IF-statement and therefore I simply need it.
I appreciate any pointers, my friends!
You could access your element directly from gridcell0 using gridcell0.querySelector('.DivOverflowNoWrap') instead, like :
var gridcell0 = document.querySelector('#x');
console.log( gridcell0.querySelector('.DivOverflowNoWrap').innerHTML );
Snippet:
var gridcell0 = document.querySelector('#x');
if (gridcell0.querySelector('.DivOverflowNoWrap') !== null) {
console.log(gridcell0.querySelector('.DivOverflowNoWrap').innerHTML);
} else {
console.log('Does not exist');
}
<div id="x">
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
</div>
With Javascript also it can be achieved but I am showing here using jQuery
$('document').ready(function() {
var div = $(".DivOverflowNoWrap");
var text = div.text();
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
The problem is how you access the div in the first place. If you do it like you described (with gridcell0.innerHTML). It will return a string. Not an HTML element.
Therefore you can't use .getAttribute or .innerHTML, because you try to apply it on a string. Access your div differently (querySelector or getElementBy...) and you will be able to use those.
You can use jquery:
$("[class='DivOverflowNoWrap']").text();
$("[class='DivOverflowNoWrap']").attr("data-originaltext")
It's pretty simple:
<html><head></head>
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
<script>
test();
function test(){
var x=document.getElementsByClassName("DivOverflowNoWrap Ellipsis")[0].getAttribute("data-originaltext");
alert(x);
}
</script>
</html>

JS alert pop up when id="something"

I have some code that has a ID that is question-number, each time I click my button it goes up numbers.
I am trying to write a small script that will show a model or a alert box once the id prints on page
"Question 2 of 40"
I so far have
CODE
<div class="columns">
<div class="column-left">
<div id="question-number" class="question-text"></div>
<div id="question-time" class="question-time"></div>
</div>
</div>
what I have tried
First attempt
<script>
function myFunction() {
var content =('#question-number').html();
if (content.indexOf("Question 2 of 40") != -1) {
alert("String Found");
}
}
</script>
Second attempt
<script>
if($('#test-view').attr('question-number').indexOf('Question 2 of 40') != -1) {
alert('here !!!');
}
</script>
Any one see why either of these attempts do not work ?
UPDATE
I just need a scrip that says if see
Question 2 of 40
on DOM the alert box
Your code is nearly working
You forgot $ in the first line.
if you just declare the function without calling it, it will never work
var content = $('#question-number').html();
if (content.indexOf("Question 2 of 40") !== -1) {
alert("String Found");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="columns">
<div class="column-left">
<div id="question-number" class="question-text">Question 2 of 40</div>
<div id="question-time" class="question-time"></div>
</div>
</div>
Your code doesn't know when to run. You need to add the following:
$(function(){ //need this line to wait for document to be ready before binding to click event.
$('#question-number').on('click', function(){
//your code here
}
});
Or
<div id="question-number" class="question-text" onclick="myFunction()"></div>
I would also check into learning how to use your browser developer tools. They will help you immensely when you have problems like this.

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.

Jquery Function only half-works in Internet Explorer

I've gut a simple function in my page for hiding/showing panes when some tabs are clicked. Simplest thing in the world, right?
Works perfectly in Firefox and Chrome, but in IE it only half works. It will hide all the sopMonthContainers, but fails to find the container with a matching ID and display it.
$('.sopTab').click(function(e){
if ($(this).hasClass("activeTab") === false){
$(".sopTab").removeClass("activeTab");
$(this).addClass("activeTab");
};
var selectionID = $(this).attr("id");
$(".sopMonthContainer").css("display", "none");
$(".sopMonthContainer#the"+selectionID).css("display", "block");
});
I'm hoping it isn't some stupid typo that I've overlooked, but I've been staring at this thing for nearly an hour trying different variations on the theme. I've tried reworking the selector IDs to make sure they're unique (hence the "the" in the selector on the last line), I've tried selecting using only ID, I've tried using different methods to hide/show... same result no matter what.
EDIT: the relevant markup. It's got some coldfusion elements, anything between ##'s is a coldfusion variable.
<div class="sopTab" id="sopContainer#DateFormat(pubdate,'mmmm')#" style="">
#DateFormat(pubdate,"mmmm")#: <span id="sum#DateFormat(pubdate,"mmmm")#">0</span>
</div>
<cfoutput query="GetProductBasicInfo">
<div class="sopMonthContainer" style="display:none;"
id="theSopContainer#DateFormat(pubdate,'mmmm')#">
[div content goes here]
</div>
</cfoutput>
Note for example this:
<div class="sopTab" id="sopContainerNovember" style="">November: <span id="sumNovember">0</span></div>
<div class="sopMonthContainer" style="display:none;" id="theSopContainerNovember">
when you click on sopTab, the selector you build is
#thesopContainerNovember
// ^
but the ID of the target is
#theSopContainerNovember
// ^
the IDs did not match(it's the uppercase and lowercase s )
I think that the last line should be
$(".sopMonthContainer #the"+selectionID).css("display", "block");
There should be a space here. But I might be wrong. It would help if you would post a link to a jsFiddle or working example.
You have an error in your page. I noticed there's some code that looks like someone has attemped to comment it out but done it incorrectly.
In your sopQuery.cfm file, change the code here:
<script language="javascript">
<!--
cfform_submit_status["productSelections"]=null;
function check_TF_productSelections( theForm ){
cfform_isvalid = true;
cfform_error_message = "";
cfform_invalid_fields = new Object();
if ( cfform_isvalid ){
return true;
}else{
alert( cfform_error_message );
return false;
}
}
//-->
</script>
To this:
<!--
<script language="javascript">
cfform_submit_status["productSelections"]=null;
function check_TF_productSelections( theForm ){
cfform_isvalid = true;
cfform_error_message = "";
cfform_invalid_fields = new Object();
if ( cfform_isvalid ){
return true;
}else{
alert( cfform_error_message );
return false;
}
}
</script>
-->
OR... If the code is supposed to be uncommented, change it to this, but note that the error will persist as the variable cfform_submit_status is not defined anywhere:
<script language="javascript">
cfform_submit_status["productSelections"]=null;
function check_TF_productSelections( theForm ){
cfform_isvalid = true;
cfform_error_message = "";
cfform_invalid_fields = new Object();
if ( cfform_isvalid ){
return true;
}else{
alert( cfform_error_message );
return false;
}
}
</script>
Presumably it's supposed to be defined here:
<script type="text/javascript" src="/bluedragon/scripts/cfform.js"></script>
But I looked and that file is empty.

Categories