Heisenberg :
I have html tables.and I would like to change it's class
by clicking itself.
When I change class,I would like to select each class by clicking button
behind them
My attempt is like below. How can I pick up style
by clicking on button
?
Thanks
$('.click_btn').on('click', function(e) {
e.preventDefault();
style = $(this); ??
})
$('.click_td').on('click', function(e) {
e.preventDefault();
$(this).AddClass(style); ??
});
.style1{
background: rgb(255, 0, 255);
border-radius: 5px;
}
.style2 {
background: rgb(0, 255, 255);
border-radius: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="click_td">color</td>
<td class="click_td">color 2</td>
</tr>
</table>
<button class="click_btn" class="style1">style1</button>
<button class="click_btn" class="style2">style2</button>
Akhil Aravind :
Using class
attribute more once is not a good practice, we can replace it with data
attribute. So on each button click, the data
attribute value is taken, then this value is added to the table td click_td
..
Now its done on button click, but this can also be replaced with click on td
;)
var $ = jQuery;
$('.click_btn').on('click', function(e) {
e.preventDefault();
style = $(this).data().style;
$('.click_td').removeClass('style1 style2').addClass(style)
})
.style1{
background: rgb(255, 0, 255);
border-radius: 5px;
}
.style2 {
background: rgb(0, 255, 255);
border-radius: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="click_td">color</td>
<td class="click_td">color 2</td>
</tr>
</table>
<button class="click_btn" data-style="style1">style1</button>
<button class="click_btn" data-style="style2">style2</button>
This is the second method, here style is copied to a variable and then applies to the td
on clicking td
var $ = jQuery;
var style ='';
$('.click_btn').on('click', function(e) {
e.preventDefault();
style = $(this).data().style;
})
$('.click_td').on('click', function(){
$(this).removeClass('style1 style2').addClass(style)
})
.style1 {
background: rgb(255, 0, 255);
border-radius: 5px;
}
.style2 {
background: rgb(0, 255, 255);
border-radius: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="click_td">color</td>
<td class="click_td">color 2</td>
</tr>
</table>
<button class="click_btn" data-style="style1">style1</button>
<button class="click_btn" data-style="style2">style2</button>