How to change img with JavaScript using radio button and switch case? - javascript

I want to have a background image depending on the checked radio button, using a switch case. However I'm not finding the right solution to get the value from the checked radio button.
Snippet of my code:
HTML:
<section class="configurator__product">
...
</section>
<label for="blue" class="hidden">Blue</label>
<input type="radio" id="blue" name="color-totebag" value="tote-blue" class="circle tote-blue">
<label for="green" class="hidden">Green</label>
<input type="radio" id="green" name="color-totebag" value="tote-green" class="circle tote-green">
<label for="black" class="hidden">Black</label>
<input type="radio" id="black" name="color-totebag" value="tote-black" class="circle tote-black">
There's more inputs, 5 in total, hence the reason I don't think using if/else is optional. But I hope it gets clear with the amount of code I'm giving here.
JavaScript:
const changeTotebagColor = () => {
let totebagColor = document.getElementsByName(`color-totebag`).value;
const $totebagImg = document.querySelector(`.configurator__product`);
switch (totebagColor) {
case `tote-blue`:
$totebagImg.style.backgroundImage = "url('assets/img/totebag_blue')";
case `tote-green`:
$totebagImg.style.backgroundImage = "url('assets/img/totebag_green')";
case `tote-black`:
$totebagImg.style.backgroundImage = "url('assets/img/totebag_black')";
}
}
changeTotebagColor();
I hope it's a bit clear to what I'm trying to figure it out. I'm new to JavaScript, so maybe I'm doing this all wrong. I've tried numerous solutions online, however I had no luck. I would also like to avoid in-line JavaScript if possible, but I'm open to any solution at this point.

As I mentioned in my comment, the way things are set up you are not actually firing your function when you click things. You call it after the function but that doesn't "watch" things.
You can resolve this in a few ways. The easiest would be (not changing to jquery or other and leaving your vanilla js alone) to simply apply an onclick to your radios.
Example:
<input type="radio" onclick="changeTotebagColor()" id="blue" name="color-totebag" value="tote-blue" class="circle tote-blue">

Related

Is there a neat way to separate checked checkbox labels in JS/jquery?

I'm working on method that has it's purpose to get elements from a form so that the form can be previewed before submitting. Currently I'm stuck on a problem where I'm trying to get labels from checked checkboxes and separate them. Getting the labels is no problem, but finding a neat way to split them with '( | )' is. I know adding an array possibly would solve my problem, but I was looking for an alternative way to do this in JS/Jquery by simply adding a built in method or similar.
JS and Jquery for what I currently have:
function previewForm() {
const previewPlace = document.getElementById('previewPlace');
let getPlaceChecked = $(':checkbox[name=placeCheckbox]:checked');
if (getPlaceChecked.next('label').text() === "") {
previewPlace.innerHTML = 'No place chosen.'
} else {
previewPlace.innerHTML = getPlaceChecked.next('label').text();
}
}
HTML (actual form):
<div class="custom-checkbox custom-checkbox-padding custom-control">
<input class="custom-control-input" id="norway" name="placeCheckbox" type="checkbox" value="Norway">
<label class="custom-control-label" for="norway">Norway</label>
</div>
<div class="custom-checkbox custom-checkbox-padding custom-control">
<input class="custom-control-input" id="sweden" name="placeCheckbox" type="checkbox" value="Sweden">
<label class="custom-control-label" for="sweden">Sweden</label>
</div>
HTML (preview):
<p class="media-description" id="previewPlace"></p>
So far I've tried simply adding space like below. I've also tried appending, but it doesn't work the way I thought it would.
previewPlace.innerHTML = getPlaceChecked.next('label').text() + " | ";
Edit: typo in if-statement
Edit1: Made a quick fiddle to better demonstrate my problem https://jsfiddle.net/d1nryuqg/
Edit2: Made changes in 'HTML (actual form)' to better fit the jsfiddle..
When you use .text() on a collection (of more than one element), it combines all of the values into a single string - there's no nice way to separate them.
Instead, you can use jquery .map to give you an array of strings for each label, then .join to separate them:
previewPlace.innerHTML = getPlaceChecked.next("label").map((i,e)=>e.innerText).toArray().join(", ")
Updated fiddle: https://jsfiddle.net/6p1h853t/

why doesn't element.attribute doesn't work in Edge?

I'm creating a small quiz type application in javascript. My html structure looks like this.
<div class="btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary btn-insight" data-target="#myCarousel" data-responseID="1">
<input type="radio" name="options" id="option1" autocomplete="off">
<h5>1</h5>
<p class="mb-0">label for 1</p>
<div class="line-bottom gradient-purple"></div>
</label>
...
</div>
I'm trying to use the custom data attribute data-responseID to determine what answer was provided by the user.
When the program starts, loop through the labels using querySelectorAll and attaching a click listener to each one.
const responseLables = document.querySelectorAll('div.btn-group-toggle > label');
responseLables.forEach(element => {
element.addEventListener('click', function(e){
const clickedResponse = element.attributes[2].value;
determineWhereToSlide(clickedResponse);
});
});
This works well in Firefox and Chrome, but doesn't in Edge. (I'm not concerned with IE 11)
determineWhereToSlide is just a function that gives an alert for now. Eventually it'll be used to push the carousel forward.
I've made a working example and you can see the issue if you open it up in different browser.
https://codepen.io/anon/pen/dLmQKZ?editors=1010
I don't get why this is happening.
*EDIT 1
I just realized that the order of the attributes are different. If you change the index value to ...attributes[1]... then it works just fine. Is there a better way to do this rather than providing an index?
Don't refer to attributes by index (even if it seems it should work, attributes were unordered at least until DOM3). Use any of:
element.getAttributeNode("data-responseID").value
element.attributes["data-responseID"].value
element.getAttribute("data-responseID")
element.dataset.responseID
You can use the getAttribute() method.
replace this
const clickedResponse = element.attributes[2].value;
to this
const clickedResponse = element.getAttribute('data-responseID')

JavaScript to Toggle Material Design Lite Switch

I have the following Material Design Lite switch in my HTML and is looking for some javascript help.
<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
<input type="checkbox" id="switch-1" class="mdl-switch__input" checked />
<span class="mdl-switch__label">USEREMAIL Subscribed</span>
</label>
Upon clicking the switch, I'd like to add:
Toggle functionality to update the checked to unchecked - like on and off switch, but is looking for JavaScript help here.
I would like to really have values of "subscribed" and "unsubscribed" as text that is displayed next to it as shown (but hardcoded in the html). Is this feasible to change dynamically?
Thanks for your time. I did find this as a reference, but it was using CheckBox.
If you refer to the mdl's source code, you will find that the check and uncheck functions are bound with label tag.
You can specify an id to label like below:
<label id="check" class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
<input type="checkbox" id="switch-1" class="mdl-switch__input"/>
<span class="mdl-switch__label">Subscribed</span>
</label>
<input type="button" value="test switch" id="btn"/>
MDL natively supports on/off status switch on button click. You can also control the status by another button.
$("#btn").click(function() {
if($('#check').is('.is-checked')) {
$('#check')[0].MaterialSwitch.off();
}
else {
$('#check')[0].MaterialSwitch.on();
}
});
To update the switch label dynamically, the code can be put like below. Bind the input's change event on page load and update label text if the on/off status changes.
//toggle label
$('#check input').change(function(){
if($(this).is(':checked'))
$(this).next().text("Unsubscribed");
else
$(this).next().text("Subscribed");
});
Here is the jsFiddle code. The answer comes a bit late for you but I hope it still helps.
Referring to the code in above question:
var myCheckbox = document.getElementById('switch-1');
myCheckbox.parentElement.MaterialSwitch.off();
…
myCheckbox.parentElement.MaterialSwitch.on();
Below code maybe solve your problem:
var isChecked = $('#switch-1').is(':checked');
if(isChecked) {
alert("subscribed");
} else {
alert("not subscribed");
}

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.

JQuery .trigger click event not working under IE

I am using the following code to route click events on an img tag to an input radio below it. The code works perfectly on Chrome and other browsers, but on IE (specifically IE 11) I must double click to get the radio selected instead of just single click to get the radio input selected. Can someone please tell me what I am doing wrong, missing here? Thanks
<script type="text/javascript">
$(document).ready(function() {
$('#Img1').click(function() {
$('#radio1').trigger('click');
});
});
</script>
<div class="imagesPrev col four center">
<label class="label_radio images" for="radio1">
<div class="labelText">
<img id="Img1"src="image1.gif" alt="Image 1" />
<input type="radio" id="radio1" name="radio1" value="image1"/>
</div>
<div style="height:10px;"></div>
Image Title <br/>
</label>
</div>
Notes:
- I also noticed that I don't have to double click as normal double click, but it has to be two clicks. Meaning one click then I can wait for like 10-15 seconds then do the 2nd click to get the click event routed to the radio input.
http://jsfiddle.net/89wTk/
You should use .prop(); when dealing with checkbox/radio inputs.
$(document).ready(function() {
$('#Img1').click(function() {
var checkBox = $("#radio1");
checkBox.prop("checked", !checkBox.prop("checked"));
});
});
Have you tried using a label tag with a for attribute for this feature instead, this could solve your problem and be more browser compatible.
<label for="radio1"><img id="Img1"src="image1.gif" alt="Image 1" /></label>
<input type="radio" id="radio1" name="radio1" value="image1"/>
I can understand if this doesn't achieve what you need, but using this method should work using HTML markup instead of jQuery
relatively horrible jsfiddle demoing this:
http://jsfiddle.net/andyface/d25KS/
I remember that some version of IE don't support clicking objects other than links or buttons :(
Perhaps try using:
$("#radio1").checked(true);
or
$("#radio1").selected(true);
as a work around
Just simple, you don't have to use any Jquery for this, just keep everything inside the label:
<label for="radio_btn">
<img id="img"src="image1.gif" alt="Image here" />
<input type="radio" id="radio_btn" name="radio1" value="image1"/>
</label>
Working here: http://jsfiddle.net/fals/3phf4/
Your code example works fine in IE11 (desktop and metro). Is it possible that there is another click event on the page that is capturing and preventing the click event on the image? Maybe something is causing the page to lose focus (first click gets window focus second clicks the image)? Try putting an alert in the click function to see if the click is getting registered. If that's not the issue, try running the body of the function in the console to see if that is the issue. You might try other ways to trigger the event, as suggested by others. Or try the jQuery .triggerHandler("click") method.
I think your problem may be with your markup. You have your image and click events inside a label.
According to w3schools:
"...if the user clicks on the text within the element, it toggles the control."
http://www.w3schools.com/tags/tag_label.asp
That toggle is perhaps messing with your javascript. Try moving the markup outside of the label and see if that helps.
That's an easy one :).
The #img1 is encapsulated inside the
<label class="label_radio images" for="radio1">
So, without the jQuery part it's already working. Now when having the jQuery part, a single click will become a double click:
1) 'for' element of label_radio
2) the trigger in jQuery part
So, for x-browser, you should not wrap the img inside the label.
Or try to cancel the event in $('#Img1').click(function(event) { ...
You have both your img and radio wrapped in label.
HTML's default behavior is that click on label triggers radio/checkbox inside.
There are two ways you can solve your problem:
Remove javascript function altogether.
If there's additional reason for javascript, change your html markup, and move radio outside of the label. Also remove for attribute, cause it triggers radio selection. Something like this:
<div class="imagesPrev col four center">
<label class="label_radio images">
<div class="labelText">
<img id="Img1"src="image1.gif" alt="Image 1" />
</div>
</label>
<input type="radio" id="radio1" name="radio1" value="image1"/>
<div style="height:10px;"></div>
Image Title
</div>
<script type="text/javascript">
$(document).on('click','.Img1',function()
{
var checkBox = $(".radio1");
checkBox.prop("checked", !checkBox.prop("checked"));
});
</script>
<img class="Img1" src="image1.gif" alt="Image 1" />
<input type="radio" class="radio1" name="radio1" value="image1"/>
I am facing the same issue and its very weird .... the workaround that is working for me is that instead of using the trigger function .. put the code which is executed in the trigger click event in a javascript function and call that function instead of trigger event ... example is given below.
For this example i will use an alert in case of a click on the element with id radio1.
Event definition
$('#radio1').on('click',function () {
alert("Hi");
})
So Instead of using $('#radio1').trigger('click'); we can put the alert in a javascript function and call the javascript function where ever i am calling the trigger click event.
Javascript function
function triggerClick(){
alert("Hi")
}
and just call this function(triggerClick()) where ever you are using $('#radio1').trigger('click');
Please let me know if this is helpfull
Try to use .click() instead of .trigger('click'):
<script>
$(document).ready(function() {
$('#Img1').click(function() {
$('#radio1').click();
});
});
</script>
it should work, see here for more info

Categories

Resources