how to call multiple images for a checkbox - javascript

The following code was a reply to a question posted last year. It’s the best example I can find to want I am looking to do. I have HTML knowledge but my JS is limited – thanks for your patience. You can view the code here. The thread can be found here.
<script>
function toggleVisibility(id) {
var el = document.getElementById(id);
if (el.style.visibility=="visible") {
el.style.visibility="hidden";
}
else {
el.style.visibility="visible";
}
}
</script>
<label for="chkemployment">Employment</label>
<input type="checkbox" id="chkemployment" onChange="toggleVisibility('imgemployment');" /><br/>
<label for="chkpopulation">Population</label>
<input type="checkbox" id="chkpopulation" onChange="toggleVisibility('imgpopulation');" />
<hr />
<img id="imgemployment" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG" style="visibility:hidden"/>
How can I get multiple images to display when a checkbox has been clicked? The images would be the same, position different.
When the images are displayed I would like to have a onclick event or mouseover that would display additional info– what is the best option for this, JS or image map (hotspots)?both? I’ve used hotspots before but only by itself not with JS. Any advice on this would be appreciated.
The following link is an example of what I am trying to achieve but on a smaller scale. http://www.cozumel.travel/learn/map.cfm

If you want to use the same code but for multiple images, you can add a function that would toggle every image you defined for the onChange event.
here is a function that would do:
function toggleMultiVisibility (a){
for (var i = 0; i < a.length; i++){
toggleVisibility(a[i]);
}
}
and here is the change you should do on the HTML:
onChange="toggleMultiVisibility(['imgemployment','imgpopulation']);"
here is a working example from your code: http://jsfiddle.net/Pu2E7/

Related

Changing input value with javascript - what went wrong?

I have a text with an input field. I want the field to start as blank, and when clicked upon, set the input's text to its correct value (saved in the "name" field, for instance).
If I do it this way, it works fine:
Buy <input type="text" name="eggs" onclick="this.value=this.name;"> tomorrow.
However, if I try to clean the DOM and move the function to a separate javascript file, it stops working:
HTML:
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
JS:
function showname(el) {
el.value = el.name;
}
function showname(el){
el.value = el.name;
}
.closeform{
width: 70px;
}
.closeform input {
width: 70px;
}
.closeform button {
width: 70px;
}
Buy
<span class="closeform">
<input type="text" name="eggs" onclick="showname(this);">
</span>
tomorrow.
I'm very new to Javascript - what am I missing here?
You say in your question:
However, if I try to clean the DOM and move the function to a separate javascript file, it stops working
Let's say you have 2 actual files in the same folder:
myscript.js contents:
function showname(el) { el.value = el.name; }
index.html contents:
<!DOCTYPE html>
<html><head><title>Demo</title>
<script src="myscript.js"></script>
</head><body>
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
</body></html>
OR
<!DOCTYPE html>
<html><head><title>Demo</title>
</head><body>
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
<script src="myscript.js"></script>
</body></html>
That should work perfectly...
However, in the comments you say:
I tried it with Fiddle - maybe the problem is in Fiddle interface.
That is where your problem was....
There is no separate javascript-file in jsfiddle.
The three code-blocks (html, js, css) get merged into one file.
Right-click the result-window in jsfiddle and look at the generated file.
Then notice the options (top right corner) from jsfiddle: by default the code is wrapped in an onload-method (suiting to the library you selected or window.onload if you are not using a library).
You can however place the script in the head or body, thereby not wrapping your code inside a function's scope (which then closes over the containing identifiers).
See http://jsfiddle.net/wf55a5qb/ for a working example.
The reason your example stack-snippet worked here on StackOverflow is that it's snippet-editor does not wrap the javascript codeblock in a (onload-like) function (when it combines the three code-blocks).
Having said and explained this, I do encourage you to set your events (Using obj.addEventListener/obj.attachEvent or the direct elm.onevent) from the/a script once the elements (that your script manipulates, place script as last element of the html-body) or page (using window.onload/etc) has loaded.
I posted this to clear up what actually went wrong so you don't make false models in your head about how javascript works (like "an external script runs in it's own scope" which no-one claimed but might be an assumption you might make) whilst still learning it!
Everything in JavaScript has a scope. Where you are defining your function, it is not visible to the input so the input doesn't know that function even exists. You can use window to make the function visible to it:
<input type="text" name="eggs" onclick="window.showname(this);"/>
window.showname = function (el)
Fiddle
I don't recommend global functions though. So then what else?
You can use the onclick function in JavaScript. To find elements in JavaScript, you use selectors. I'm using getElementById() this will get an element by it's id. A list of selectors are here
<input id="my_input" type="text" name="eggs"/>
Then in JavaScript:
document.getElementById('my_input').onclick = function () {
//Use this to refer to the element
this.value = this.name;
};
Fiddle
When doing this. Make sure all your code is wrapped in a window.onload. This will make sure the code is run at the right time:
window.onload = function () {
//Your code
};
JSFiddle automatically puts your code in this.

Using Javascript to display an input (A number) from a user to a div

I have looked at the other questions that are asking similar things to this question however when I attempted to create my own I can't get it to work properly and i dont understand why. It's only very basic before I introduce it into a more complex system I just wanted to try and get the functionality done.
This is my HTML;
<div id="test2">
Please enter a number: <input type="number" id="RValue1">
<button id="test" onclick="R1Value()">Change Value</button>
</div>
<div id="ShowR1"></div>
And this is the JavaScript;
function R1Value() {
var t = document.getElementById("RValue1");
var div = document.getElementById('ShowR1');
div.innerHTML = t.value;
}
I have made this fiddle to save time and so you can have a look at it,
http://jsfiddle.net/2ufnK/52/
I can't see why this doesn't seem to work so if anyone can see why I would really appreciate it. Thanks.
Try it without the button:
Try out this: http://jsfiddle.net/2ufnK/56/
Type in the text, then you can just call the, ".value", method to get its text. Then everything else works the way you've written it.

onmouseover issue -- original picture completely disappears

My problem is that I'm not able to change picture based on different events, in my case, onmouseover. I'm using JavaScript and html5 standard.
Below is the affected html:
<img alt="" height="300" width="162" id="bronze" class="badges" src="bilder/Bronze160x310.png">
which is supposed to be reliant on the following piece:
<label class="block">
<input name="Radio" type="radio" id="b1" onmouseover='updatePic("pictures/hi_again.png")' onchange="enableProceed(); updatePrice();" value="2.9">
<span style="cursor:pointer">test</span>
</label>
I only have trouble with the onmouseover event. I haven't tested it thoroughly, but it seemed to work fine with onchange events.
The following is the JavaScript code:
function updatePic(newPic) {
document.getElementById("bronze").src = newPic;
}
When I run this the original picture becomes unavailable even if I have not begun any mouseover. I used a switch-system for my JavaScript before, but the same problem occured.
Thanks in advance.
JSFiddle: http://jsfiddle.net/xfkjL3as/3/
I believe I have achieved what you are attempting to do in this JSFiddle.
DEMO: http://jsfiddle.net/xfkjL3as/1/.
The HTML is as follows:
<img src="http://theunleashedreviewboard.files.wordpress.com/2013/08/angry-face.png" id="myImage">
<div>
<input type="radio" id="myRadioButton" value="100" />
<label for="myRadioButton">My Radio Button</label>
</div>
The JavaScript is as follows:
function updateImageSource(src)
{
var myImage = document.getElementById("myImage");
myImage.src = src;
}
var myRadioButton = document.getElementById("myRadioButton");
myRadioButton.addEventListener("mouseover", function(){
updateImageSource('http://www.worldpeace-uk.org/wp-content/uploads/2013/07/smiley-face.jpg');
}, false);
I have used JavaScript to attach the mouseover event to the radiobutton HTML element.
Sidenote: It is generally a better practice to separate your JavaScript code from your HTML. While HTML provides you attributes such as onmouseover to achieve this, I would recommend to keep the JavaScript code in a separate file (and link it).
This question answers how to link a separate JavaScript file.

Possible IF statement with Javascript?

I'm working on a .net website and I have a bit of a situation.
Say I have...
<input type="text" class="name" id="name">
<p></p>
<input type="text" class="surname" id="surname">
<p>Error!</p>
What Id like to do, using javascript, is detect that the second paragraph tag says 'Error!' and add a class to the input tag before it.
I know this seems like a bit of a strange way of working but any advice would be greatly appreciated!
Hi all, the adivce and answers i was given worked fine on a fresh page on jsfiddle only i cant seem to get them to work on my actual site.
My P and input tags are constructed like this....
<li class="yourdetli">
<label class="yourdet">Street Name</label>
<input type="text" id="ctl00_ContentPlaceHolder1_TB_SName" name="ctl00$ContentPlaceHolder1$TB_SName">
<span style="color: Red; display: none;" class="errorp" id="ctl00_ContentPlaceHolder1_RequiredFieldValidator6">
<p>You must complete this field</p></span>
</li>
and my JS is...
<script type="text/javascript">
$(document).ready(function() {
$('p:contains("You must complete this field")').prev('input').addClass('error');
});
</script>
only for some reason it doesnt seem to add my class, can anybody see why?
You can use
$('p:contains("Error")').prev('input').addClass('error');
Maybe try
$("p:eq(1):contains('Error!')").prev('input').addClass('error');
You can check the text value of the second <p> tag by using jQuery. You'll need a selector that finds it (in this example, it is the last <p> tag).
if ($("p").last().text() == "Error!") {
$("input#surname").addClass("myClass");
// do other stuff here
}
Try -
if ($("input#surname").next("p:contains('Error!')").length > 0) {
$("input#surname").addClass('yourclass');
}
I'd recommend adding the error css class to your validator's CssClass property so that its already rendered server side. This way if you change your error message, you won't have to change any javascript to display it.
<asp:RequiredFieldValidator ID="requiredValidator" CssClass="error" ControlToValidate="..." ErrorMessage="You must complete this field"/>
Or if you're looking to style all of your validators with the same class, you can add the following script to your master page.
$(document).ready(function()
{
if (Page_Validators != null)
{
for (i = 0; i < Page_Validators.length; i++)
{
Page_Validators[i].className = "error";
}
}
});
See http://www.jrummell.com/blog/index.php/2009/08/apply-the-same-css-class-to-all-validators-in-a-web-project/ for more information.

How to get selected icefaces datatable row using radiobutton?

How can I select a row in icefaces datatable using radio button?
I tried with the following
<h:selectOneRadio styleClass="none" valueChangeListener="#{bean.setSelectedItem}"
onclick="dataTableSelectOneRadio(this);">
<f:selectItem itemValue="null" />
</h:selectOneRadio>
And my javascript
function dataTableSelectOneRadio(radio) {
var id = radio.name.substring(radio.name.lastIndexOf(':'));
var el = radio.form.elements;
for (var i = 0; i < el.length; i++) {
if (el[i].name.substring(el[i].name.lastIndexOf(':')) == id) {
el[i].checked = false;
}
}
radio.checked = true;
}
In another post I got an answer that I should replace form.name with form.id. However after that I am getting error
radio.form is undefined
var elements = radio.form.elements;
Could someone help me how to resolve this issue.
I would like to select one row in icefaces datatable using radio button.
Any help is highly appreciable.
Thanks
Posting my generated html source
See here is jsf code for radio button
<h:selectOneRadio valueChangeListener="#{bean.setSelectedItem}"
id="reqselect" onclick="dataTableSelectOneRadio(this);">
<f:selectItem itemValue="null" />
</h:selectOneRadio>
My heartfelt apologies for posting in correct html source, I was testing some thing else and thus wrong source got posted. Pasted below is my correct html source, kindly see if you could find something.
You should use the ice:selectOneRadio with spread layout:
<ice:selectOneRadio id="myRadioId" layout="spread" ... />
<ice:dataTable ... >
<ice:column ...>
<ice:radio for="myRadioId" ... />
</ice:column>
...
</ice:dataTable>
Here's how the generated HTML of each radio button look like:
<table id="crud:tab_cr:9:_id53" border="0" onkeypress="dataTableSelectOneRadio(this);">
<tr>
<td>
<input type="radio" name="crud:tab_cr:9:_id53" id="crud:tab_cr:9:_id53:_1" value="null" onkeypress="dataTableSelectOneRadio(this);Ice.util.radioCheckboxEnter(form,this,event);" />
<label for="crud:tab_cr:9:_id53:_1">null</label>
</td>
</tr>
</table>
So IceFaces is apparently rendering a whole HTML table around the radio button and putting the JS function on the <table> as well. The JS function clearly doesn't belong there at all (apart from the fact that onkeypress is incorrect, it should be onclick).
The <h:selectOneRadio> doesn't render a whole table around by default. This can only mean that you were actually using <ice:selectOneRadio> or that the IceFaces replaced the standard renderer for <h:selectOneRadio>. You need to fix it in this corner. Either replace by <h:selectOneRadio> or report a bug to IceFaces guys that their radio renderer is incorrectly putting the JS function on <table> element as well.

Categories

Resources