I'm trying to get the second dropdown value based on the first dropdown value using JavaScript.
At first, the second dropdown is in hidden mode and activated by choosing the first dropdown and then the second value is out by just showing data based on the first dropdown selected value.
- Depts has deptId as primary key.
- Bir has deptId as foreign key.
I'm trying to get Bir items where deptId == selectedItem
on Depts.
How can I make this work?
Here's my view :
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Dept">Dept</label>
<select class="form-control required" id="Dept" name="Dept" onchange='checkvalue(this.value)'>
<option value="0">Dept</option>
<?php
if(!empty($Depts))
{
foreach ($Depts as $rl)
{
?>
<option value="<?php echo $rl->deptId ?>"><?php echo $rl->deptName?></option>
<?php
}
}
?>
</select>
</div>
</div>
<div class="col-md-6" >
<div class="form-group" id="bir" style='display:none'>
<label for="bir">Bir</label>
<select class="form-control required" id="bir" name="bir" onchange='checkvalues(this.value)'>
<option value="0">Pilih Bir</option>
<?php
if(!empty($birs))
{
foreach ($birs as $rl)
{
?>
<option value="<?php echo $rl->birId ?>"><?php echo $rl->birName ?></option>
<?php
}
}
?>
</select>
</div>
</div>
</div>
Here's my JavaScript :
function checkvalue(val)
{
if(val != 0)
{
document.getElementById('biro').style.display ='block';
}
}
First of all, you have a duplicate
id
value in your HTML. I assume thediv
should not havebir
butbiro
asid
attribute value.You could then add a
data-dept
to theoption
elements that you add dynamically to the second drop down, and give it the value of thedeptId
:Then in the script, read out that value with
dataset.dept
(make sure you have corrected the div'sid
attribute in the HTML).Here is a snippet (without PHP):