Reputation: 3628
I have 5 radio buttons and depending of which one is selected I want to change the href
link of an image, which sends you to another page. Example: I selected the first radio button. When I click the image, the page "gallery" opens. When I select the second radio button and press the image, it'll open the page "about me"... is there any solution for this with JavaScript?
This is my radio set:
<input checked="" type="radio" name="slider" id="slide1">
<input type="radio" name="slider" id="slide2">
<input type="radio" name="slider" id="slide3">
<input type="radio" name="slider" id="slide4">
<input type="radio" name="slider" id="slide5">
<input type="radio" name="slider" id="slide6">
and this is the button:
<div id="down_icon2">
<a href="">
<img src="images/down_icon.png">
</a>
</div>
Upvotes: 0
Views: 7002
Reputation: 58
Create a function to check which radio button is set, the function sets the desired link.
<input checked="" type="radio" name="slider" id="slide1">
<input type="radio" name="slider" id="slide2" >
<input type="radio" name="slider" id="slide3">
<input type="radio" name="slider" id="slide4">
<input type="radio" name="slider" id="slide5">
<input type="radio" name="slider" id="slide6">
<a href="" onclick='myFunction()' id="myLink">MyLink</a>
<script>
function myFunction() {
if(document.getElementById('slide1').checked) {
document.getElementById('myLink').href = "test.php";
}
}
</script>
you can do the same with the image src
Edit: it is just the case for the first radio button, you have to add the test for the other buttons.
Upvotes: 4
Reputation: 377
That is the answer, it's just use native javascript.it can wrote better if you use extra lib like jQuery.
https://jsfiddle.net/mham9ons/
just use your html:
<input type="radio" name="slider" id="slide2" data-href="xxx1">
<input type="radio" name="slider" id="slide3" data-href="xxx2">
<input type="radio" name="slider" id="slide4" data-href="xxx3">
<input type="radio" name="slider" id="slide5" data-href="xxx4">
<input type="radio" name="slider" id="slide6" data-href="xxx5">
<div id="down_icon2"><a href=""><img src="images/down_icon.png"></a></div>
add these code:
var sliders = document.getElementsByName('slider');
var linkWrapper = document.getElementById('down_icon2');
for (var i in sliders){
if(sliders[i].addEventListener){
sliders[i].addEventListener('click', function(){
linkWrapper.childNodes[0].setAttribute('href', this.getAttribute('data-href'));
});
}
}
Upvotes: 1
Reputation: 2064
<input type="radio" data-image="http://www.placecage.com/200/300" name="slider" id="slide1">
add a data-image to all the slides with the image you want. Then with Jquery you can do this:
$("input").click(function () {
var clickedRadio = $(this).attr("data-image");
$("img").attr("src", clickedRadio);
})
If you click any input it sets the src of the image to the data-image of the clicked item ;) Note this uses Jquery library
Also here is a working example codepen
Upvotes: 1