Conor Conor - 3 months ago 8
HTML Question

Image as check box

I have 2 images.

What i want to do is to make it clickable and selectable.

If i select the first one the other should not be selected.

and if i click a button it should print the vaalue of the selected image on

<p>
tag

This is the code which i got after searching a lot :



$('#img1').click(function() {
var a = $('#img1');
//A if else condition should be here to know wheather it already contain the class
a.addClass('clicked')
})
$('#img2').click(function() {
var a = $('#img2');
//A if else condition should be here to know wheather it already contain the class
a.addClass('clicked')
})
$('button').click(function() {
var a = $('#img1').val();
var b = $('#img2').val();
$('p').html(/*The value of the selected image*/)
})

.clicked {
box-shadow: 0 0 10px 2px grey;
}
img:hover {
cursor: pointer;
box-shadow: 0 0 10px 2px grey;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img src="http://www.w3schools.com/howto/img_avatar.png" width="100px" height="100px" id="img1" value="noo">
<img src="http://www.w3schools.com/howto/img_avatar2.png" width="100px" height="100px" id="img2" value="yes"><br>
<button>
Copy
</button>
<p>

</p>





Jsfiddle

Thanks

Answer

I have updated your js use $('#img1').removeClass('clicked'); on click functions

$('#img1').click(function() {
var a = $('#img1');
 $('#img2').removeClass('clicked');
 //A if else condition should be here to know wheather it already contain the class
  a.addClass('clicked')
})
 $('#img2').click(function() {
    var a = $('#img2');
  $('#img1').removeClass('clicked');
//A if else condition should be here to know wheather it already contain the class
 a.addClass('clicked')
})