Alimin
Alimin

Reputation: 2727

How to using jquery child() method to adding class in many elements?

I have written a function to mark and control div elements with red border. It is controlled with select option element. The options are kotak1,kotak2,etc. So when I choose kotak1 then associated div border become red. How to restore that div element to black border again when I change other option?

HTML

<div id="group-select">
    <select id="select_kotak">
        <option selected>Pilih Kotak</option>
    </select>
</div>
<br>
<div id="group-kotak">
    <div class="kotak-nonaktif">Kotak 1</div>
    <div class="kotak-nonaktif">Kotak 2</div>
    <div class="kotak-nonaktif">Kotak 3</div>
    <div class="kotak-nonaktif">Kotak 4</div>
</div>
.kotak-nonaktif {
    height: 100px;
    width: 100px;
    border: 1px solid black;
    float: left;
    margin-left: 1px;
}
.kotak-aktif {
    height: 100px;
    width: 100px;
    border: 3px solid red;
    float: left;
    margin-left: 1px;
}
$(document).ready(function () {
    set_pasar_option();
});

function set_pasar_option() {
    for (i = 1; i < 5; i++) {
        var option = document.createElement("option");
        option.text = "Kotak" + i;
        option.value = "value" + i;
        option.id = "id" + i;
        var select = document.getElementById("select_kotak");
        select.appendChild(option);
        option.addEventListener('click', function () {
            aktif_kotak(this.id);
        });
    }
}

function non_aktif_kotak() {
    var allkotak = document.getElementById('groupkotak').children();
    $(allkotak).addClass("kotak-nonaktif");
}

function aktif_kotak(id) {
    //non_aktif_kotak(); 
    id = id.substr(2, 4);
    id = parseInt(id) - 1;
    var kotak_aktif = document.getElementById('group-kotak').children[id];
    $(kotak_aktif).addClass("kotak-aktif");
}

FIDDLE

Upvotes: 1

Views: 51

Answers (1)

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

Just add this line in your aktif_kotak() function:

$(kotak_aktif).siblings().removeClass("kotak-aktif");

like this in the last.

function aktif_kotak(id){
  //non_aktif_kotak(); 
  id=id.substr(2, 4);
  id=parseInt(id)-1;
  var kotak_aktif=document.getElementById('group-kotak').children[id];
  $(kotak_aktif).addClass("kotak-aktif");   
  $(kotak_aktif).siblings().removeClass("kotak-aktif"); 
}   

DEMO

Upvotes: 1

Related Questions