JS alert pop up when id="something" - javascript

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.

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>

HTML element not detected in external .js file [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
My HTML code:
<div class="container">
<div class="question-card">
<h1 id="question1">This is the question</h1>
</div>
<div class="answer-choices">
<div class="row1">
<span class="choice1" id="one" onclick="choice1()">One</span>
<span class="choice2" onclick="choice2()">Two</span>
</div>
<div class="row2">
<span class="choice3" onclick="choice3()">Three</span>
<span class="choice4" onclick="choice4()">Four</span>
</div>
</div>
<button id="btn" onclick="next()">Next</button>
My js code:
function clickNextText(){
document.getElementById("question1").innerHTML="Answer recorded, Click next to proceed"
} //This is working fine
var str
element = document.getElementById('btn');
if (element != null) {
str = element.value;
}
else {
str = null;
}
console.log(str) //This is however returning null.
I don't understand what is wrong here. Moreover every element with an id after the div with class answer-choices isn't detected. While the script code when placed in .html itself works fine.
Likely your javascript is running before the page has loaded. Try wrapping your whole javascript logic in a function and running it on window.load.
i.e.
window.load = function () {
// your code here
}
first change your function name on click from next() to clickNextText()
<button id="btn" onclick="clickNextText();">Next</button>
then use this code in javascript instead of :
function clickNextText(){
document.getElementById("question1").innerHTML="Answer recorded, Click next to proceed"
}
document.onload = function(){
var str
element = document.getElementById('btn');
if (element != null) {
str = element.value;
}
else {
str = null;
}
console.log(str);
};

javascript if condition is not working

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

Hide/show images button JS

I have a webpage where i have 3 images and I have a button to hide those images all at once on click, and then show them(this part is not implemented yet). I have a JS function for hiding them but it is not working and I have no idea why. So this is part of my code:
<div id="left"><img id="leftimage" name="leftimage" src="pic1url.jpg" style=
"visibility:visible"></div>
<div id="centerright">
<div id="center"><img id="centerimage" name="centerimage" src="pic2url.jpg"
style="visibility:visible"></div>
<div id="right"><img id="rightimage" name="rightimage" src="pic2url.jpg"
style="visibility:visible"></div>
</div><script type="text/javascript">
var hideShowButton = document.getELementById("hideShowButton");
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage"; center:"centerimage"; right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{ document.getElementById(allImages[image]).style.visibility = 'hidden';
document.getElementById(allImages[image+"1"]).style.visibility = 'hidden';
document.getElementById(allImages[image+"2"]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
</script>
<div id="buttons">
<input id="hideShowButton" type="button" value="Hide Pics">
</div>
Before reading the answer, I highly suggest you learn how to use the browser's console. It will print all the errors that make your JavaScript code to crash. I also suggest you take some time to read JavaScript tutorials :)
There are many things wrong with your code. First, there is a typo "getELementById" (L is uppercase instead of lowercase). Second, you need to place the script tags bellow your button. Third, when creating an object, you should separate it's properties using commas (,) not semicolons (;) . Finally, you made a false use of the for loop. Just to help you out, here is the corrected code but don't expect people to do that for you every time. You need to find mistakes like these on your own in the future :)
<div id="left">
<img src="pic1url.jpg" id="leftimage" style="visibility:visible" />
</div>
<div id="centerright">
<div id="center">
<img src="pic2url.jpg" id="centerimage" style="visibility:visible"/>
</div>
<div id="right">
<img src="pic2url.jpg" id="rightimage" style="visibility:visible"/>
</div>
</div>
<div id="buttons">
<input type="button" value="Hide Pics" id="hideShowButton" />
</div>
<script type="text/javascript">
var hideShowButton = document.getElementById("hideShowButton");
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage", center:"centerimage", right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{
document.getElementById(allImages[image]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
</script>
Use can use diplay none or block property of css to hide and show any view respectively
<img id="one" src="pic1url.jpg" style="display:none;" />
Through javascript you can use this
document.getElementById(one).style.display = 'none';
Sorry, but your code is a bit messy. Why are you using a for statement if then you try to hide every image every time?
By the way, you're misusing the for...in statement. AllImages is a asociative array with no numeric indexes. for (var image in AllImages), image will be 'left', then 'center', then 'right' (the names of the properties of the object you're using). So a statement like
AllImages[image+1]
will return 'undefined' and your code will throw an error. Your code should look like this:
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage"; center:"centerimage"; right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{
document.getElementById(allImages[image]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
By the way, I suggest you to read some documentation about loops in javascript, like MDN

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