Reputation: 23
I have got three boxes (box1, box2, box3). Box2 and box3 are the same, they just show a border when clicked on (selection). Only one item can be selected at the same time. I got this so far.
Now i would like that in box one appears a text where it says= " You clicked on..." and then there should be written "I am Box 1" or "I am Box 2".
I know it is probably a simply thing, but I just dont get it, I tried so many things now.
HTML:
<div class="showbox">
<a>
When I cklick on one of the yellow boxes, I would like the content of this element to be changed. The result should be "Okay, you chose Box 1 (or Box 2, depens on what I clicked on).
</div>
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
CSS:
.showbox{
height: 14rem;
width: 14rem;
background-color: grey;
float:left;
}
.box{
height: 4.5rem;
width: 4.5rem;
background-color: yellow;
margin: 1rem;
}
#box1, #box2{
float: left;
}
.borderClass{
border-style: solid;
border-width: 2px 2px 2px 2px;
}
JS:
var box1 = "I am Box 1";
$('.box').click( function(){
if ( $(this).hasClass('borderClass') ) {
$(this).removeClass('borderClass');
} else {
$('.box').removeClass('borderClass');
$(this).addClass('borderClass');
}
});
Please look here:
https://jsfiddle.net/j7rdtqvc/
Upvotes: 1
Views: 28
Reputation: 648
if you can add some attributes to your div elements, here you go:
<div class="box" id="box1" data-id="1"></div>
<div class="box" id="box2" data-id="2"></div>
and script should be:
$('.box').click( function(){
if ( $(this).hasClass('borderClass') ) {
$(this).removeClass('borderClass');
} else {
$('.box').removeClass('borderClass');
$(this).addClass('borderClass');
}
if ($(this).data('id') == 1) {
$('.showbox').html('Okay, you chose Box 1.')
} else {
$('.showbox').html('Okay, you chose Box 2.')
}
});
But if you can't add any other attributes, this is the way:
$('.box').click( function(){
if ( $(this).hasClass('borderClass') ) {
$(this).removeClass('borderClass');
} else {
$('.box').removeClass('borderClass');
$(this).addClass('borderClass');
}
var id = $(this).attr('id').split('box')[1];
$('.showbox').html('Okay, you chose Box ' + id + '.')
});
Upvotes: 0
Reputation: 217
You can try following code I just change the text based on click of box.
$('.box').click( function(){
var box_number = 0;
if( $(this).attr('id')== 'box1' ) {
box_number = 1;
}else if( $(this).attr('id')== 'box2' ){
box_number = 2;
}
$(this).html('<p>Okay, you chose Box '+box_number+'</p>');
if ( $(this).hasClass('borderClass') ) {
$(this).removeClass('borderClass');
} else {
$('.box').removeClass('borderClass');
$(this).addClass('borderClass');
}
});
Upvotes: 0