Last active
April 1, 2021 16:11
-
-
Save achjailani/fe1b528378be001c4b36771b5fdd19cb to your computer and use it in GitHub Desktop.
JS auto change element with select element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>JS - Test</title> | |
</head> | |
<body> | |
<h3>JS - Document</h3> | |
<table> | |
<tr> | |
<th>No</th> | |
<th>Name</th> | |
<th>category</th> | |
<th>Side</th> | |
</tr> | |
<?php | |
$no = 1; | |
for($i=1; $i<10; $i++){ | |
?> | |
<tr> | |
<td id="nomor"><?=$i++;?></td> | |
<td>Hello</td> | |
<td> | |
<div id="category"> | |
<select class="category"> | |
<option value=""> -- Pilih --</option> | |
<option value="pendidikan">Pendidikan</option> | |
<option value="politik">Politik</option> | |
<option value="entertaimen">Entertaimen</option> | |
<option value="bola">Bola</option> | |
<option value="ekonomi">Ekonomi</option> | |
<option value="budaya">Budaya</option> | |
</select> | |
</div> | |
</td> | |
<td> | |
<div class="subcategory" class="subcategory"> | |
<select> | |
<option> -- Pilih --</option> | |
<option><?=$no++;?></option> | |
</select> | |
</div> | |
</td> | |
</tr> | |
<?php } ?> | |
</table> | |
<script> | |
const data = { | |
pendidikan: [ | |
"SD", "SMP", "SMA", "SMK", "Sarjana", "Magister" | |
], | |
politik: [ | |
"Provinsi", "Kota", "Kabupaten" | |
], | |
entertaimen: [ | |
"artis", "musik", "film" | |
], | |
bola: [ | |
"Liga primar", "FIFA" | |
], | |
ekonomi: [ | |
"Pemerintah", "Masyarakat" | |
], | |
budaya: [ | |
"Lokal", "Luar" | |
] | |
}; | |
let category = document.getElementsByClassName("category"); | |
for (let i = 0; i < category.length; i++) { | |
category[i].addEventListener("change", function(e) { | |
let sub = document.getElementsByClassName("subcategory")[i]; | |
let select = document.createElement("select"); | |
let option = document.createElement('option'); | |
option.innerHTML = "-- Choose --"; | |
select.appendChild(option) | |
for(let y=0; y<data[category[i].value].length; y++) { | |
let opt = document.createElement('option'); | |
opt.value = data[category[i].value][y]; | |
opt.innerHTML = data[category[i].value][y]; | |
select.appendChild(opt) | |
} | |
sub.innerHTML = ""; | |
sub.appendChild(select) | |
}); | |
} | |
</script> | |
</body> | |
</html> | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment