getElementById() .innerHTML/.src - javascript

I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great

Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>

Related

JS exstract part of URL from multiple form fields

I have a form that has multiple fields all with the same class. These are populated with URL's that follow the same structure. I am trying to extract the same section from each URL. So far var res = x.split('/')[5]; will achieve this but only for the first URL. I can also use var x = document.querySelectorAll(".example") to change all the url's but I cannot find the correct way to combine both of these function. so far my code looks like this:
script>
function myFunction() {
var x = document.querySelectorAll(".example").innerHTML;
var res = x.split('/')[5];
var i;
for (i = 0; i < x.length; i++) {
x[i].innerHTML = res;
}
}
</script>
I have looked around but can't find a solution that fits. Thanks in advance for your help.
So loop over the HTML Collection, this is making assumptions based on code.
// Find all the elements
var elems = document.querySelectorAll(".example")
// loop over the collection
elems.forEach(function (elem) {
// reference the text of the element and split it
var txt = elem.innerHTML.split("/")[5]
// replace the text
elem.innerHTML = txt
})
<div class="example">1/2/3/4/5/a</div>
<div class="example">1/2/3/4/5/b</div>
<div class="example">1/2/3/4/5/c</div>
<div class="example">1/2/3/4/5/d</div>
<div class="example">1/2/3/4/5/e</div>
<div class="example">1/2/3/4/5/f</div>

document.getElementById().innerHTML wont update with a 2d array

I'm trying to update multiple <div> without refreshing the whole page and figured that if I cycle through an array using the index I can achieve that, but it's not working at all.
However when I replace event[index]['fullName'] in the prevEvent function with index, the page gets updated.
How do I update the page contents without refreshing the whole page?
<script type="text/javascript" >
var index=0;
//pass php array to javascript
var event= <?php echo json_encode($event); ?>;
document.getElementById("fullName").innerHTML = event[index]['fullName'];
document.getElementById("emailAddress").innerHTML = event[index]['emailAddress'];
document.getElementById("phoneNumber").innerHTML = event[index]['phoneNumber'];
document.getElementById("childName").innerHTML = event[index]['childName'];
document.getElementById("theater").innerHTML = event[index]['theater'];
document.getElementById("movie").innerHTML = event[index]['movie'];
document.getElementById("eventDate").innerHTML = event[index]['eventDate'];
document.getElementById("eventTime").innerHTML = event[index]['eventTime'];
document.getElementById("eventType").innerHTML = event[index]['eventType'];
document.getElementById("numOfPeople").innerHTML = event[index]['numOfPeople'];
document.getElementById("partyRoomBook").innerHTML = event[index]['partyRoomBook'];
document.getElementById("partyRoomTime").innerHTML = event[index]['partyRoomTime'];
document.getElementById("description").innerHTML = event[index]['description'];
document.getElementById("specialAttention").innerHTML = event[index]['specialAttention'];
function prevEvent(){
index--;
document.getElementById("fullName").innerHTML = event[index]['fullName'];
}
</script>

How to display random images from array [duplicate]

This question already has answers here:
Getting a random value from a JavaScript array
(28 answers)
Closed 5 years ago.
So im creating an app that helps you decide on a movie to watch. one of the functions on the app is a randomizer button which randomly displays a movie based on the genre you selected but not sure how to display the image. heres what i have so far. Thank you!
<body>
<button id='randomBut'>RANDOMIZE</button>
<div id='movieImg'><img src='movie1.svg'></div>
</body
<script>
var randomizer = document.getElementById("randomBut");
var randimg = document.getElementById("movieImg");
var movieimages = ["movie1.svg", "movie2.svg", "movie3.svg"];
document.getElementById("movieImg").innerHTML = movieimages;
randomizer.addEventListener("click", function(){
var randimg = document.createElement("img");
randimg.src = "movieimages" ;
</script>
put the id on the image and then create a random number generator. use that random number and choose the image from the array and assign it to the image src
<button id='randomBut'>RANDOMIZE</button>
<div><img id='movieImg' src='http://placehold.it/100x100'></div>
<script>
var randomizer = document.getElementById("randomBut");
var randimg = document.getElementById("movieImg");
var movieimages = ["http://placehold.it/100x100", "http://placehold.it/150x100", "http://placehold.it/100x150"];
randomizer.addEventListener("click", function(){
var randNum = Math.floor(Math.random() * movieimages.length) + 0
randimg.src = movieimages[randNum] ;
});
</script>

Get image names in html using JavaScript

How can I pick up image name in html using JavaScript? I searched google and there are some documents about how to get image name on <img> tag,
var filename = tag.replace( /^.*?([^\/]+)\..+?$/, '$1' );
But it return just one name of images. What I'm going to do is get all images name. Imagine the html below,
<html>
<body>
<div class="imagebox">
<img src="/some/path/imageOne.jpg">
<img src="/some/path/imageTwo.jpg">
<img src="/some/path/imageThree.jpg">
</div>
</body>
</html>
after magic, return
imageOne, imageTwo, imageThree. How can I do this..?
Add the following Javascript code at the bottom of your html page :
Solution for browser environment :
var images = document.getElementsByTagName('img');
var images_urls = [];
var images_names = [];
var tmp;
for(var i=0;i < images.length;i++){
images_urls[i] = images[i].getAttribute('src');
tmp = images[i].getAttribute('src').split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
and now images_names is an array containing the image names, in this case imageOne,imageTwo and imageThree
Solution for Node.js environment:
lets say you have images url stored in images variable like this :
var images = ["/some/path/imageOne.jpg", "/some/path/imageTwo.jpg", "/some/path/imageThree.jpg"];
you can use Regex, but in this case you can do it easily without using Regex, just split each image url and grab the last part of it, pretty simple, something like this :
var images_names = [];
var tmp
for(var i=0;i < images.length;i++){
tmp = images[i].split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
It is the same solution for both Browser and Node.js environment except for the way you get the elements.
Hope this helps.

Pass variables to code <input type="image" src="imageSrc;" >

hope someone can help a noob. Many thanks in advance.
I have an index page with links to hundreds of other pages holding song words.
I have built each song page but it would be MUCH simpler to have one MASTER page that took a variable from the index page and found the corresponding words (which exist as png graphics.)
I have sorted Step 1 - I can pass a variable from the index page to the master page using:
<a href="javascript: window.open('MUSIC/beatles/mastertest2.html?song=ER', '_parent')">
where song=ER is the variable to display the words for Eleanor Rigby. For Step 2, I can also retrieve that information in the master page with:
var imageSrc = (qs("song")+".png"); document.write(imageSrc);
which will display the text ER.png which is the name of the image I want to display.
For Step 3 I am trying to get this same variable read into:
<input type="image" src="imageSrc;">
to display the picture. I have searched this and other forums for days now and nothing suggested works for me. I could be missing out an essential early step in the coding?
Update:
My master html file has this code to retrieve the variable:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
And it uses this code to disply the variable (appended with .png) just to prove to me that it is getting through:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
Then I am trying to feed the variable into a routine to display the png selected. The next script doesn't work but I am thrashing about trying anything right now:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
<input type="image" src="#imageSrc;" border="0" value="Notes" onClick="placeIt(); showIt()">
<input id="song-image" type="image">
var imageSrc = 'ER.png';
var input = document.getElementById('song-image');
input.src = imageSrc;
If you have already <input type="image"> in your HTML page, you must add an id and then set it's src attribute with
HTML:
<input id="song-image" type="image">
JS:
var imageSrc = 'http://www.lorempixel.com/200/100';
var input = document.getElementById('song-image');
input.src = imageSrc;
JSFiddle for testing.
If I understood you right, its very simple. Are you looking for this?
var input = document.createElement('input');
input.type = 'image';
input.src = imageSrc;
document.body.appendChild(input);
If you can print the variable imageSrc using document.write, then you can use it like shown above.

Categories