I want to make Active if the Countries I check is Inactive. But I didnt know how, here’s my code.
PS: I use mobile phone for now, so that Snippet is not avail. For those who extract my code through Snippet is much appreciated.
This is the example, because the only problem is how to make any function if you click the respective element or div. Like for example, if I check the checkbox in 2nd div, there’s something happen in 2nd div only. Then if I didn’t check the others div, it nothing happens or affected.
const Countries = ["Philippines", "New York", "Singapore"];
function createList() {
const liTag = $('.Handler');
for (let i = 0; i < Countries.length; i++) {
const List = `
<ul id="CountryList">
<li>
<div class="NameOfCountry">
<input type="checkbox" class="Check">
<p class="CountryName">Hello</p>
<p class="InActive">Inactive</p>
</div>
</li>
</ul>
`;
var elem = $(List);
elem.find('.CountryName').html(Countries[i]);
elem.find('.Check').change(function() {
//Create a code that if the checkbox is Check, the word inactive makes Active on Respective Element.
})
liTag.append(elem);
}
}
createList();
* {
margin: 0;
padding: 0;
outline: none;
box-sizing: border-box
}
body {
background: #40fff5;
}
.Handler {
width: 100%;
padding: 12px;
}
ul li {
list-style: none;
}
.NameOfCountry {
background: blue;
width: 100%;
display: flex;
justify-content: space-between;
gap: 6px;
border-radius: 8px;
align-items: center;
padding: 8px;
margin-top: 6px;
}
.CountryName {
color: white;
font-size: 18px;
font-weight: bold;
width: 100%;
text-align: center;
}
.InActive {
background: white;
border-radius: 5px;
color: red;
font-size: 11px;
font-weight: bold;
width: 30%;
padding: 5px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="Handler"></div>
3
Answers
I added a few things
Added the
status
class to yourtag
added a few things to your
.change
function to toggle between ‘Active’ and ‘Inactive’ and change the background color based on the checkbox state.If I’ve understood your question correctly, your goal is to toggle the ‘InActive’ text to ‘Active’ based on the state of the checkbox within any given row.
To do this, you can use a single delegated event handler which accepts an Event object as an argument. You can determine which checkbox triggered the event from that Event and traverse the DOM to update its related
p
element.Below is a working example. Note that I added some classes to the content to make identifying elements easier, and I also moved the HTML out of the JS in to the HTML to maintain a good Separation of Concerns.