Image display with checkbox - javascript

I want the user to be able to display images by selecting the image that they want to display using a checkbox. I have tried to do that but the image doesn't seem to display when selected
function testdisplay() {
var image = document.getElementsByTagName("img")
var src2=image[2].getAttribute("src");
var img1 = document.getElementById("check-option8");
var bg = document.getElementById("container");
if (img1.checked) {
bg.src=src2
}
}
}
<div id="container">
<img id="dolphin1" class="dolphin" src="../images/dolphins/image1.png" alt="dolphin 1" title="dolphin 1">
<img id="dolphin2" class="dolphin" src="../images/dolphins/image2.png" alt="dolphin 2" title="dolphin 2">
<img id="dolphin3" class="dolphin" src="../images/dolphins/image3.png" alt="dolphin 3" title="dolphin 3">
</div>
<div id="toggle-components">
<fieldset>
<legend>Choose image to display</legend>
<input type="checkbox" id="check-option1" checked="checked"><label for="check-dolphin1">diving down</label>
<input type="checkbox" id="check-option8" onclick="if(this.checked){testdisplay()}" )><label for="check-dolphin8">jumping up</label>
<input type="checkbox" id="check-option5"><label for="check-dolphin5">take off</label>
<input type="checkbox" id="check-option3"><label for="check-dolphin3">jumping together</label>
</fieldset>
</div>

I try to update you code, so that you can understand easily:
Major changes in your code is:
make an array to keep the image source
make some changes testDisplay function too.
link of jsfiddle
var imgArray = [];
imgArray.push("http://reviewnepal.com/socialevents/thumb/google_photo.jpg");
imgArray.push("http://reviewnepal.com/socialevents/thumb/google_photo.jpg");
imgArray.push("http://reviewnepal.com/socialevents/thumb/google_photo.jpg");
function testdisplay() {
var src2 = imgArray[1];
var bg = document.getElementById("container");
if (document.getElementById("check-option8").checked)
bg.src = src2;
else
bg.src = "";
}
<img id="container" />
<div id="toggle-components">
<fieldset>
<legend>Choose image to display</legend>
<input type="checkbox" id="check-option1" checked="checked"><label for="check-dolphin1">diving down</label>
<input type="checkbox" id="check-option8" onclick="debugger; testdisplay();" )><label for="check-dolphin8">jumping up</label>
<input type="checkbox" id="check-option5"><label for="check-dolphin5">take off</label>
<input type="checkbox" id="check-option3"><label for="check-dolphin3">jumping together</label>
</fieldset>
</div>

Related

How to get the checked radio button in JS?

I have seen that this works for most of users, but for some reason it doesn't for me. I use Google Chrome.
radioBut = document.querySelector(".rad-design")
getColor = function(){
for (i=0; i<radioBut.length; i++){
if (radioBut[i].checked){
console.log(radioBut[i)
}
}
Html
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design"></div>
</label>
</div>
</form>
The selector should be document.querySelectorAll to get inputs as array and you should target to .rad-input class which is the input and not .rad-design which is the label. Also you should use checked for the inputs to make the input checked, its not check. Also you cannot set checked to two inputs with same name. If thats done only the last input with that name will be checked.
Working Fiddle
const radioBut = document.querySelectorAll(".rad-input")
getColor = function () {
for (i = 0; i < radioBut.length; i++) {
if (radioBut[i].checked) {
console.log(radioBut[i])
}
}
}
<form id="rad">
<div class="radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" checked name="colList">
<div class="rad-design">One</div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design">Two</div>
</label>
</div>
<button type="button" onclick="getColor()">getColor</button>
</form>
document.querySelector returns just one element not an array/list, so in the for loop at i<radioBut.length radioBut.length is undefined, you need to use document.querySelectorAll() instead.
Also I noticed you have selected the div and not the input and you have a couple of syntax errors.
Maybe this can help you:
const radioBut = document.querySelectorAll(".rad-input")
const getColor = function(){
for (let i=0; i<radioBut.length; i++){
if (radioBut[i].checked){
console.log(radioBut[i].value)
}
}
}
console.log(getColor())
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" value='A' name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" value='B' name="colList" checked>
<div class="rad-design"></div>
</label>
</div>
</form>
Another options is to use the form element functionality
const form = document.getElementById('rad');
const getColor = function(){
return form.colList.value;
}
console.log(getColor())
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" value='A' name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" value='B' name="colList" checked>
<div class="rad-design"></div>
</label>
</div>
</form>

if else or switch html checkbox get value

what coding html if else or switch for checkbox? Example when tick 1 checkbox 'text' statement will appear. But if tick 3 checkbox the statement change to 'another text'. Given my coding; If tick 'cat' checkbox 'British shorthair' checkbox will appear and click again 'cute' text appear. How to make it if two or more checkbox tick the text change example like 'super cute'
<script type="text/javascript">
function ShowHideDiv(Cat) {
var dvCat = document.getElementById("bigCat");
bigCat.style.display = Cat.checked ? "block" : "none";
console.log(Cat.value)
console.log("Text Inside LABEL:" + Cat.parentNode.textContent)
}
</script>
<label for="Cat">
<input type="checkbox" id="Cat" onclick="ShowHideDiv(this)" value="cat"/> Cat
</label>
<script type="text/javascript">
function ShowHideDiv2(Rabbit) {
var bigRabbit = document.getElementById("bigRabbit");
bigRabbit.style.display = Rabbit.checked ? "block" : "none";
console.log(Rabbit.value)
console.log("Text Inside LABEL:" + Rabbit.parentNode.textContent)
}
</script>
<label for="Rabbit">
<input type="checkbox" id="Rabbit" onclick="ShowHideDiv2(this)" value="Rabbit"/> Rabbit
</label>
<div id="bigCat" style="display: none">
<label>
<input type="checkbox" id="bigSubCat" /> British shorthair
</label>
<label>
<p id="subCats1" ></p>
</label>
<script>
document.getElementById("bigSubCat").addEventListener("click", function() {
document.getElementById("subCats1").innerHTML = "Cute";
});
</script>
<label>
<input type="checkbox" id="bigSubCat" /> Exotic Shorthair
</label>
</div>
<div id="bigRabbit" style="display: none">
<label>
<input type="checkbox" id="bigSubRabbit" /> White Rabbit
</label>
<label>
<input type="checkbox" id="bigSubRabbit" /> Black Rabbit
</label>

Javascript / jQuery UI: Changing element img src from an array of images based on current img src

I have a canvas element containing an image, which is initially a Green Square. I'm trying to change the displayed image based on the input from two sets of jQuery UI radio buttons: the first set allows the user to select a colour and has 3 options (Red/Green/Blue), and the second set allows the user to select a shape (Circle/Square).
My Javascript code declares an array of images, one of which is then assigned to display in the canvas element when a button option is checked, like so:
var images = new Array();
images[0] = new Image();
images[0].src = '../../../media/images/Red-Circle.png';
images[1] = new Image();
images[1].src = '../../../media/images/Red-Square.png';
images[2] = new Image();
images[2].src = '../../../media/images/Green-Circle.png';
images[3] = new Image();
images[3].src = '../../../media/images/Green-Square.png';
images[4] = new Image();
images[4].src = '../../../media/images/Blue-Circle.png';
images[5] = new Image();
images[5].src = '../../../media/images/Blue-Square.png';
$(function () {
$("#colour").buttonset();
$("#shape").buttonset();
});
$('#red').click(function () {
if ($('#red').is(':checked')) {
$("#container #image img").attr("src", images[1].src);
}
});
$('#green').click(function () {
if ($('#green').is(':checked')) {
$("#container #image img").attr("src", images[3].src);
}
});
$('#blue').click(function () {
if ($('#blue').is(':checked')) {
$("#container #image img").attr("src", images[5].src);
}
});
HTML:
<div id="container">
<div id="image">
<img src="media/images/Green-Square.png" />
</div>
</div>
<form>
<div id="colour">
<input type="radio" id="red" name="radio">
<label for="colour1">Red</label>
<input type="radio" id="green" name="radio" checked="checked">
<label for="colour2">Green</label>
<input type="radio" id="blue" name="radio">
<label for="colour3">Blue</label>
</div>
</form>
<form>
<div id="shape">
<input type="radio" id="circle" name="radio">
<label for="circle">Circle</label>
<input type="radio" id="square" name="radio" checked="checked">
<label for="square">Square</label>
</div>
</form>
I've only got as far as being able to select the colour. When it comes to selecting the shape, I want to change the displayed image to retain the previous choice of colour (so that for example, if Red was the currently selected colour and the user then selected Circle, the image displayed would change to a Red Circle and not a Green or Blue Circle). Conversely, if the user selected the shape first and THEN selected a colour, I want the displayed image to retain the choice of shape.
I have a vague idea that the solution might be to do with adding 1 or subtracting 1 from the array index based on what the current index is - but I have no clue how to implement this. I'm relatively new to JS so any help would be appreciated. Thanks.
You can store your images in an 'images' object and access them by string (ex images["RedSquare"]) I've put together a fiddle. The image links are broken but if you inspect the page you can see the src is being changed properly.
https://jsfiddle.net/5wv5ym5p/
HTML:
<div id="container">
<div id="image">
<img src="media/images/Green-Square.png" />
</div>
</div>
<form>
<div class="shape-config" id="colour">
<input type="radio" id="red" name="radio">
<label for="red">Red</label>
<input type="radio" id="green" name="radio" checked="checked">
<label for="green">Green</label>
<input type="radio" id="blue" name="radio">
<label for="blue">Blue</label>
</div>
</form>
<form>
<div class="shape-config" id="shape">
<input type="radio" id="circle" name="radio">
<label for="circle">Circle</label>
<input type="radio" id="square" name="radio" checked="checked">
<label for="square">Square</label>
</div>
</form>
JS (needs JQuery):
var images = {};
images["RedCircle"] = new Image();
images["RedCircle"].src = '../../../media/images/Red-Circle.png';
images["RedSquare"] = new Image();
images["RedSquare"].src = '../../../media/images/Red-Square.png';
images["GreenCircle"] = new Image();
images["GreenCircle"].src = '../../../media/images/Green-Circle.png';
images["GreenSquare"] = new Image();
images["GreenSquare"].src = '../../../media/images/Green-Square.png';
images["BlueCircle"] = new Image();
images["BlueCircle"].src = '../../../media/images/Blue-Circle.png';
images["BlueSquare"] = new Image();
images["BlueSquare"].src = '../../../media/images/Blue-Square.png';
$(function () {
$("#colour").buttonset();
$("#shape").buttonset();
});
$('.shape-config input').click(function () {
var colourId = $("#colour input:checked").attr("id");
var colour = $('label[for='+colourId+']').text();
var shapeId = $("#shape input:checked").attr("id");
var shape = $('label[for='+shapeId+']').text();
$("#container #image img").attr("src", images[colour+""+shape].src);
});
Here is an plunker for what you are trying to do.
https://plnkr.co/edit/jMvjJCxHZzr9dxw5B6RR?p=preview
the function you will require are
$('#circle').change(function () {
if ($('#circle').is(':checked')) {
var a = jQuery.grep(images, function( n ,i) {
if ( n.src == $("#container #image img").attr("src") )
return i;
})[0];
var index = images.indexOf(a);
$("#container #image img").attr("src", images[index-1].src);
}
});
$('#square').change(function () {
if ($('#square').is(':checked')) {
var a = jQuery.grep(images, function( n ,i) {
if ( n.src == $("#container #image img").attr("src") )
return i;
})[0];
var index = images.indexOf(a);
$("#container #image img").attr("src", images[index+1].src);
}
The color select button logic is not correct as well please use this logic there as well.
Why bother using arrays/indexes and storing it at all?
https://jsfiddle.net/0Lqgc3vx/
HTML
<img id="img" src="Green-Square.png" />
<form>
<input type="radio" name="colour" value="Red">
<label for="colour1">Red</label>
<input type="radio" name="colour" value="Green" checked="checked">
<label for="colour2">Green</label>
<input type="radio" name="colour" value="Blue">
<label for="colour3">Blue</label>
</form>
<form>
<input type="radio" name="shape" value="Circle">
<label for="circle">Circle</label>
<input type="radio" name="shape" value="Square" checked="checked">
<label for="square">Square</label>
</form>
JS
$("input[name='colour']").change(function () {
$("#img").attr("src", this.value + "-" + $("input[name='shape']:checked").val() + ".png");
});
$("input[name='shape']").change(function () {
$("#img").attr("src", $("input[name='colour']:checked").val() + "-" + this.value + ".png");
});

jquery next() reference to specific ul's li

I'm working on a multi stage form with the following enabling the next/previous button to transit the form submission from one stage to the other:
$("input[name='next']").click(function(){
var output = validate();
if(output) {
var current = $("#signup-step.active");
var next = current .next(); //Just use .next() here to get the nextSibling of this li
if(next.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+next.attr("id")+"-field").show();
$("input[name='back']").show();
$("input[name='finish']").hide();
$(".active").removeClass("active");
next.addClass("active");
/* if($(".active").attr("id") == $("#signup-step.li").last().attr("id")) {
$("input[name='next']").hide();
$("input[name='finish']").show();
} */
if ( next.is(':last-child') ) {
$("input[name='next']").hide();
$("input[name='finish']").show();
}
}
}
});
$("input[name='back']").click(function(){
var current = $(".active");
var prev = $(".active").prev("#signup-step.li");
if(prev.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+prev.attr("id")+"-field").show();
$("input[name='next']").show();
$("input[name='finish']").hide();
$(".active").removeClass("active");
prev.addClass("active");
/*if($(".active").attr("id") == $("#signup-step.li").first().attr("id")) {
$("input[name='back']").hide();
}
*/
if ( next.is(':last-child') ) {
$("input[name='back']").hide();
}
}
});
By #signup-step:li I'm trying to refer to the li elements in a specific UL element because there two other UL element on the page: 1) UL of main menu, 2) UL of sidebars. Now since the main menu's UL comes before the form itself, the next/back button activate the menu items of the main menu rather the form stages. So being able to specify the UL referred will resolve this.
Kindly advise on the the correct for mat for selecting #signup-step:li in the code above?
Here is the form:
<ul id="signup-step">
<li id="Initiate" class="active">Initiate</li>
<li id="Strive">Strive</li>
<li id="End">End</li>
</ul>
<form name="frmRegistration" id="signup-form" method="post" enctype="multipart/form-data" action="sendemail.php">
<div id="initiate-field">
<label>Name of Organization</label><span id="coyname-error" class="signup-error"></span>
<div><input type="text" name="coyname" id="coyname" class="demoInputBox"/></div>
<label>Certificate of Incorporation No.</label><span id="cacnum-error" class="signup-error"></span>
<div><input type="text" name="cacnum" id="cacnum" class="demoInputBox"/></div>
<label>Registered Office Address</label><span id="regofficeaddy-error" class="signup-error"></span>
<div>
<textarea cols="30" rows="4" name="regofficeaddy" id="regofficeaddy" class="demoInputBox" class = "max10"></textarea>
</div>
<label>Operations Address</label><span id="opsaddy-error" class="signup-error"></span>
<div>
<textarea cols="30" rows="4" name="opsaddy" id="opsaddy" class="demoInputBox" class = "max10"></textarea>
</div>
</div>
<div id="strive-field" style="display:none;">
<label>Location of workshop/facility if different from office address given in the Structure Section:</label><span id="facilityloc-error" class="signup-error"></span>
<div>
<textarea cols="60" rows="8" name="facilityloc" id="facilityloc" class="demoInputBox" class = "max10"></textarea>
</div>
<label>Size of facility (in sq meters):</label><span id="facilitysize-error" class="signup-error"></span>
<div><input type="text" name="facilitysize" id="facilitysize" class="demoInputBox"/></div>
<label>Does your organization own or hire equipment:</label>
<div>
<input type="radio" name="facilityownhire" id="facilityownhire" value="Own"> Own
<input type="radio" name="facilityownhire" id="facilityownhire" value="Hire"> Hire <span id="facilityownhire-error" class="signup-error"></span>
</div>
</div>
<div id="end-field" style="display:none;">
<label>Does your Organization have an HSE Manual?</label>
<div>
<input type="radio" name="hsemanual" id="hsemanual" value="Yes"> Yes
<input type="radio" name="hsemanual" id="hsemanual" value="No"> No <span id="hsemanual-error" class="signup-error"></span>
</div>
<div id="hseevidenceBOX">
<label>If yes, please attach evidence</label><span id="hseevidence-error" class="signup-error"></span>
<div>
<input type="file" name="vendorfile[]" id="hseevidence" class="demoInputBox" />
</div>
</div>
<label>Does your Organization have a Safety Policy?</label>
<div>
<input type="radio" name="orgsafepolicy" id="orgsafepolicy" value="Yes"> Yes
<input type="radio" name="orgsafepolicy" id="orgsafepolicy" value="No"> No <span id="orgsafepolicy-error" class="signup-error"></span>
</div>
</div>
<div>
<input class="btnAction" type="button" name="back" id="back" value="Back" style="display:none;">
<input class="btnAction" type="button" name="next" id="next" value="Next">
<input class="btnAction" type="submit" name="finish" id="finish" value="Send" style="display:none;">
</div>
</form>
Thanks everyone for responding. I solve the problem of conflict with the main menu of the page I change the .active class to .here in the UL HTML, CSS and jquery script. I also reliazed from this fiddle http://jsfiddle.net/GrahamWalters/sgNH4/2/ i gained from another thread that the next("#signup-step.li"); should be next("#signup-step li");
UL HTML
<ul id="signup-step">
<li id="Initiate" class="active">Initiate</li>
<li id="Strive">Strive</li>
<li id="End">End</li>
</ul>
CSS
#signup-step li.here{background-color:#FF0000;}
.here{color:#FFF;}
JQUERY
$("#next").click(function(){
var output = validate();
if(output) {
var current = $(".here");
var next = $(".here").next("#signup-step li");
if(next.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+next.attr("id")+"-field").show();
$("#back").show();
$("#finish").hide();
$(".here").removeClass("here");
next.addClass("here");
if($(".here").attr("id") == $("#signup-step li").last().attr("id")) {
$("#next").hide();
$("#finish").show();
}
}
}
});
$("#back").click(function(){
var current = $(".here");
var prev = $(".here").prev("#signup-step li");
if(prev.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+prev.attr("id")+"-field").show();
$("#next").show();
$("#finish").hide();
$(".here").removeClass("here");
prev.addClass("active");
if($(".here").attr("id") == $("li").first().attr("id")) {
$("#back").hide();
}
}
});

Getting all child input elements within a div

I am trying to get all the values of the input fields. The issue is all of the <input type=radio/> are dynamic and can increase or decrease at any time.
So I am starting with the main DI and going from there. The problem I have now is I am not getting the input radio buttons values.
So here are the steps I am intending to accomplish:
If any radio button is selected, pass its value to the checkbox value,
If the radio button is selected and the checkbox is not selected, do not pass to the checkbox value
I am looking for a solution in JavaScript only - do not use jQuery
Here is my jsFiddle code
HTML
<div style="display: block;" id="mymainDiv" class="fullFloat">
<input type="hidden" value="1" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">UPS<a class="fRight" onclick="localG('10',false,0,false,'UPS','1','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_UPS"><div class="loadingcheckout"></div></div>
<div id="Price_UPS">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11098" id="deliveryMethodId_1" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
UPS Ground (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="UPS_11098">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="UPS">
</div>
<input type="hidden" value="2" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">Standard<a class="fRight" onclick="localG('20',false,0,false,'Standard','2','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_Standard"><div class="loadingcheckout"></div></div>
<div id="Price_Standard">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11117" id="deliveryMethodId_2" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
Standard Delivery - 2-3 Day Delivery at Ground Rate (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="Standard_11117">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="Standard">
</div>
<input type="hidden" value="3" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">FedEx<a class="fRight" onclick="localG('190',false,0,false,'FedEx','3','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_FedEx"><div class="loadingcheckout"></div></div>
<div id="Price_FedEx">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11088" id="deliveryMethodId_3" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
FedEx Ground (Order by 8:00 PM EST)
</span>
<div class="wrapRight">
<div id="FedEx_11088">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="FedEx">
</div>
</div>
<input type="checkbox" name="shipmode" id="shipmode" value="" onclick="getpref('mymainDiv');">Get Value
JS Code
This executes when the checkbox is clicked:
function getpref(val) {
var wr = document.getElementById(val);
childElements = wr.childNodes;
//alert(childElements);
for(var i = childElements.length-1; i>=0; i--){
var elem = childElements[i];
console.log(elem.id);
if(elem.id && elem.id.indexOf(val+'_')==0){
elem.style.display = 'block';
}
}
//alert(val);
}
You can directly access input nodes in your DIV with getElementsByTagName
function getpref(val) {
var divNode = document.getElementById(val);
var inputNodes = divNode.getElementsByTagName('INPUT');
for(var i = 0; i < inputNodes.length; ++i){
var inputNode = inputNodes[i];
if(inputNode.type == 'radio') {
//Do whatever you want
if(inputNode.checked) {
//Do whatever you want
}
}
}
}
Example: http://jsfiddle.net/88vp0jLw/1/
You can use getElementsByName to get you all of the radio buttons by name='deliveryMethodId' and then go from there:
function getpref(val) {
var radioButtons = document.getElementById(val).getElementsByName("deliveryMethodId");
for(var i = radioButtons.length-1; i>=0; i--)
{
var radioButton = radioButtons[i];
if(radioButton.checked)
console.log(radioButton.id + " is selected ");
}
}

Categories