Here is the radio selection:
<ul id="radio-attribute" class="radio-attribute">
<li class="radio-attribute">
<label for="1" class="radio-attribute">
<input type="radio" id="1" name="Choose color" value="36" onClick="change_image(this.id)">
<img src="images/Red.jpg" alt="Red SE1017" title=" Red SE1017 " width="25" height="25" />
</label>
</li>
<li class="radio-attribute">
<label for="2" class="radio-attribute">
<input type="radio" id="2" name="Choose color" value="157" onClick="change_image(this.id)">
<img src="images/Orange.jpg" alt="Orange" title=" Orange " width="25" height="25" />
</label>
</li>
</ul>
This works fine.
I am looking to swap the images displayed based on the radio selection. The radio selection will vary so I was planning to use the id for this.
The display container:
<div id="piGal" style="float: left;">
<a href="http://www.example.com/images/main.jpg">
<img src="images/main.jpg" alt=" Seals" title=" main image " width="250" height="106" />
</a>
</div>
This displays fine on initial load.
I am trying to use an array I build dynamically with php so the javascript looks like this:
function change_image(radioID) {
var images = ["main.jpg", "Red.jpg", "Orange.jpg"];
document.getElementById("piGal").innerHTML = "<img src='images/'+ images[radioID]>";
}
I can get this working using AJAX, but it will not allow me to have a pop up with it, rather will open in a new page. I have been trying to use this so I can use a modal. I am very new to javascript like this though.
First of all, if this form should be sent to php I strongly discourage you to use names with spaces. I once experienced some kind of problems with php and I still don’t know why.
Your problem might be in change_image():
function change_image(radioID) {
var images = ["main.jpg", "Red.jpg", "Orange.jpg"];
document.getElementById("piGal").innerHTML = "<img src=\"images/"+ images[radioID] +"\" />";
}
You haven’t generated the right HTML code for the img. You were making a mess with HTML attribute quotes and JavaScript string quotes. Try it now.
Now if
image[radioID] == "main.jpg"
JavaScript will generate
<img src="images/main.jpg" />
Which is correct HTML. Your code would generate the string as is, which is not correct HTML, and your browser fails silently.
**EDIT: ** to open the popup:
window.open("main.jpg", "imgWindow",
"location=no,width=600,height=600,scrollbars=yes,top=100,left=700,resizable=no");
The first argument is the URL of the file to open, the second argument is a unique name for the window (if you open another file with the same window name, the same window will be selected), the third argument is a list of parameters separated by commas (I guess the names are intuitive). You can put it in a function callable on the onClick event of the img tag your creating in change_image()
Related
I have a matrix of images. Each image currently fills a specific field with information. Code for one image below.
<img src="components/com_safety101/images/a2.jpg" width="72" height="32" border="0" onclick="document.getElementById('jform_pre_control_risk').value = '10: Undesirable'; " />
Is there a way that each image could fill three fields with different information? Not sure if you can stack the document.get ElementById calls?
The statement in the onclick attribute can contain any number of JavaScript statements.
You can write a whole program in it if you want - just that it's going to look terrible.
It is more advisable to put what you want to achieve with the onclick inside a separate function:
<a href="#riskrating1" data-toggle="tab">
<img src="components/com_safety101/images/a2.jpg"
width="72" height="32" border="0"
onclick="handleOnClickFor(this)" />
</a>
and add a JavaScript function:
<script type="text/javascript">
function handleOnClickFor (element){
// 'element' would be the DOM Object for the <img> tag,
// differentiate different images with arguments like this
// Note that the arguments can be a string, number, object ...
document.getElementById('jform_pre_control_risk').value = '10: Undesirable';
}
</script>
You would extract the code to a javascript function:
<a href="#riskrating1" data-toggle="tab">
<img
src="components/com_safety101/images/a2.jpg"
width="72" height="32" border="0"
onclick="populateFields()" />
</a>
<script type="text/javascript">
function populateFields() {
document.getElementById('jform_pre_control_risk').value = '10: Undesirable';
// Populate other fields here
document.getElementById('other_id').value = 'some other value';
}
</script>
I have a search input box, and on top of that I have an image/logo.
What is the most efficient way to change image/logo every time user refresh the page ?
<img class="" id="Default Logo" src="/img/logo/logo_3.png" alt="logo" width="150px" >
<span class="input-icon input-icon-right">
<input id="searchbox" placeholder="Enter SKU or name to check availability " type="text" />
<i class="ace-icon fa fa-search red"></i>
</span>
Right now, I use logo_3.png, but I have 10 of them.
If you are using backend (and I think you are), then just build the output randomly every time when a user visit your page.
In case of PHP for example:
<img id="Logo" src="/img/logo/<?php echo $random_logo_name; ?>.jpg" alt="logo">
Set your img src strings in a JavaScript array and get a random element from the array on page load. Assuming they are all the same width.
var image = images[Math.floor(Math.random()*images.length)];
First off, your ID needs to be one word.
<img id="default-logo" src="/img/logo/logo_1.png" alt="logo" ... />
As long as all of your images are named "logo_*.png", you're fine to randomize the number. Otherwise, you'll need to add the file names into an array, and select the index randomly.
$(document).ready(function () {
var image = $('#default-logo'),
num = ((Math.random() * 10 | 0) + 1);
image.prop('src', '/img/logo/logo_' + num + '.png');
});
Already answered in here:
How to reload/refresh an element(image) in jQuery
Changing img src through jQuery: image won't refresh
How to refresh the src of <img /> with jQuery?
Force refresh an image in jquery mobile
But basically, every time you refresh a page, you should call your backend image server with an appended random number to it (like: img_1, img_2, img_3...)
Solution : I use php function : rand()
<img src="/img/logo/<?php echo rand(1,10); ?>.jpg" alt="logo" width="200px" >
Output - notice image will randomly change !
this is my first question on Stack Overflow, I'm new to Javascript (have been teaching myself Python to get a feel for coding) and thought I'd try my hand at a simple web app to see how easy it is to translate my knowledge of Python into Javascript.
Basically the app will let you know when your favourite fruit etc is in season. So I have a list of checkboxes on one page 'fruitpicker.html' and corresponding images on another 'seasonalguide.html' (The images are just pictures of a calendar with the fruits season shaded etc).
I have a cookie that persists the checkbox state and a piece of external JS that toggles image visibility depending on the state of its corresponding checkbox.
Most of the cookie someone else was using on the web, so it works great, however the image vis JS is giving me trouble.
I've written what I think it should be but it didn't work and no matter how much I tinker around with it, nothing happens.
I'm sure it's something really dumb but anyway, here's the code...
The broken image vis JS:
function toggleVisibility(checkId, imageId) {
var imgEl = document.getElementById(imageId);
var checkEl = document.getElementById(checkId);
if (checkEl.checked) {
imgEl.style.visibility="hidden";
imgEl.style.display="none";
}
else {
imgEl.style.visibility="visible";
imgEl.style.display="inline-block";
}
}
By the way, if the line: var checkEl = document.getElementById(checkId);
is deleted the code works but image state doesn't persist. This is as far as I have gotten.
A few of the checkboxes in fruitpicker.html:
<html>
<head>
<title>Fruit Picker</title>
<script type="text/javascript" src="cookie.js"></script>
</head>
<body onload="restorePersistedCheckBoxes();">
<label for= "chklogo">Braeburn</label>
<input type= "checkbox"
id= "chkBraeburn"
onChange= "toggleVisibility('braeburnItem');
toggleVisibility('braeburnSeason');
persistCheckBox(this);" /><br>
<label for= "chklogo">Fuji</label>
<input type= "checkbox"
id= "chkFuji"
onChange= "toggleVisibility('fujiItem');
toggleVisibility('fujiSeason');
persistCheckBox(this);" /><br>
<label for= "chklogo">Golden Delicious</label>
<input type= "checkbox"
id= "chkgolldenDelicious"
onChange= "toggleVisibility('goldenDeliciousItem');
toggleVisibility('goldenDeliciousSeason');
persistCheckBox(this);" /><br>
<label for= "chklogo">Granny Smith</label>
<input type= "checkbox"
id= "chkGrannySmith"
onChange= "toggleVisibility('grannySmithItem');
toggleVisibility('grannySmithSeason');
persistCheckBox(this);"/><br/>
</body>
</html>
And here is the Seasonal Guide page:
<html>
<head>
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript" src="imageVisibility.js"></script>
</head>
<body>
<img id="imgGuide"
src="Images/Calendar/calendarHeader.png"
align="left"/>
<img id="braeburnItem"
src="Images/Produce/Fruit/BraeburnApple.png"
style="float:left; display:none;" />
<img id="braeburnSeason"
float="top"
src="Images/InSeason/InSeasonApr.png"
align="left"
style="display:none"/>
<img id="fujiItem"
src="Images/Produce/Fruit/FujiApple.png"
style="float:left; display:none;" />
<img id="fujiSeason"
float="top"
src="Images/InSeason/InSeasonMar.png"
align="left"
style="display:none;"/>
<img id="goldenDeliciousItem"
src="Images/Produce/Fruit/GoldenDeliciousApple.png"
style="float:left; display:none;"/>
<img id="goldenDeliciousSeason"
src="Images/InSeason/InSeasonFeb.png"
align="left"
style="display:none;"/>
<img id="grannySmithItem"
src="Images/Produce/Fruit/GrannySmithApple.png"
style="float:left; display:none;"/>
<img id="grannySmithSeason"
src="Images/InSeason/InSeasonApr.png"
align="left"
style="display:none;"/><br>
<table width="170px" height="70px">
<tr>
<td>
<a href="Main.html" id="back" title="about" class="button">
<img src="Images/Buttons/backButton.png" align="right">
</td>
</tr>
</table>
</body>
</html>
The question was getting long so I didn't include the cookie, but I can if it's useful.
Any help is appreciated, Thanks
I'm noticing two issues here.
First off, you're using two separate pages, but document.getElementById can only access the elements of the page you're on. So, your lines:
var imgEl = document.getElementById(imageId);
var checkEl = document.getElementById(checkId);
have to fail, because they are trying to access elements in the two pages. Whichever page you're running the script on, one of those lines will return null. Your question doesn't describe how the two separate HTML files relate to each other, so I can't help you fix this (Does the first load the second whenever a checkbox is clicked, or are the two pages loaded in frames or iframes of a parent page?).
The second issue is that your toggleVisibility function is defined with two parameters, but your code (for example):
onChange= "toggleVisibility('grannySmithItem');
toggleVisibility('grannySmithSeason');
calls the method (twice) with only one parameter. If we're talking about the same function (you might have a different function definition on each of the two pages), then the function can never identify the correct image, because the imageId is never supplied.
Error :
Microsoft JScript runtime error: 'ctl00_ContentPlaceHolder1_txtAdmDate' is undefined
Code :
<input ID="txtAdmDate" runat="server" readonly="readonly" type="text"
tabindex="23" clientidmode="AutoID" />
<a href="#" onclick="showCalendarControl(ctl00_ContentPlaceHolder1_txtAdmDate)">
<img border="0" src="images/SmallCalendar.jpg"
style="width: 20px; height: 20px" /></a>
Javascript:
function showCalendarControl(textField) {
calendarControl.show(textField);
}
html rendered Source :
<input name="ctl00$ContentPlaceHolder1$txtAdmDate" type="text" id="ctl00_ContentPlaceHolder1_txtAdmDate" readonly="readonly" tabindex="23" />
<a href="#" onclick="showCalendarControl(ctl00_ContentPlaceHolder1_txtAdmDate)">
<img border="0" src="images/SmallCalendar.jpg"
style="width: 20px; height: 20px" /></a>
Problem :
Though the html rendered source shows that the id of control is ctl00_ContentPlaceHolder1_txtAdmDate and the same is passed to the javascript function error is generated.I have tried setting clientidmode to Autoid and static but nothing works. Need help from you guys to solve this issue.
First, it looks like you are inside a Master Page or User Control (hence the name mangling), and in that case you should not assume how the name will be mangled by hardcoding it. If you use a different master page or move the User Control to another page, this the mangled name could be different. To resolve that, use the ClientID property instead.
Also, you can't just reference the control directly by name to have Javascript find it, because the controls are not global variables. Instead, you can use document.getElementById to look get a handle to the control.
<a href="#" onclick="showCalendarControl(document.getElementById('<%=txtAdmDate.ClientID%>')">
When you say this:
showCalendarControl(ctl00_ContentPlaceHolder1_txtAdmDate)
You're assuming that ctl00_ContentPlaceHolder1_txtAdmDate is a variable but it isn't a variable, it is just a DOM id attribute. You could say this:
showCalendarControl(document.getElementById('ctl00_ContentPlaceHolder1_txtAdmDate'))
to turn it into an object inside the function call or you could send an ID to showCalendarControl and let it turn the ID into an object:
onclick="showCalendarControl('ctl00_ContentPlaceHolder1_txtAdmDate')"
and then adjust showCalendarControl:
function showCalendarControl(textFieldId) {
var textField = document.getElementById(textFieldId);
calendarControl.show(textField);
}
I've got the following code (example):
<body>
<div id="obj1">
<span id="obj2">
<img src="someimage2.jpg" class="image" />
</span>
<img src="someimage2.jpg" class="image" />
</div>
<img src="someimage3.jpg" class="image" />
<button onClick="getUrl();">Get it?</button>
</body>
I need JavaScript to get the url of the image which is located at body >> obj1 >> obj2 >> img
I can imagine a markup similar to this...
function getUrl() {
alert(document.getElementById("obj1").getElementById("obj2").img.getAttribute("src"));
}
But (what a surprise!) it doesn't work, apparently.
Any help? :)
What I am trying to do (if this helps):
I've got an input and a button. Say I type this into input:
Cyber Dragon
This code is called upon the button is pressed:
'do something' or here: document.write('<input id="src" /><button onClick="getImg();">Get</button><br /><iframe src="http://yugioh.wikia.com/wiki/' + document.getElementById("src").value.replace(" ","_") + '"></iframe>');
Then, I'd need to get the image's src attribute from the site (which is "http://yugioh.wikia.com/wiki/Cyber_Dragon" in this case), but it's not all that simple.
The site stores it in an img, not an ID's Div, and can only be told from other images by its hierarchy position. Also, the img's src is complicated and not universal. For example, one's adress would be
http://images3.wikia.nocookie.net/__cb20060929013607/yugioh/images/thumb/e/e5/CyberDragonCRV-EN-SR.jpg/300px-CyberDragonCRV-EN-SR.jpg
and another would look like
http://images1.wikia.nocookie.net/__cb20090402012158/yugioh/images/thumb/a/a6/HonestLODT-EN-ScR-1E.png/300px-HonestLODT-EN-ScR-1E.png
Since you can only have one element in any document with any given id, you only need the one getElementById. You can then use getElementsByTagName to find the image and then the src property to find the image's source:
var imgsrc = document.getElementById('obj2').getElementsByTagName('img')[0].src;