Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

icelander's avatar

Onchange event, getting a value from a select tag and changing the visibility of other elements

i have tried several methods to achieve this aim but to no avail. pls can someone simply assist me with a dummy example to do it. once an option is selected, I just want it to display a select box with values pertaining to the value of the earlier selected option. for instance, the initial select option contains just engine and exhaust. once any one is clicked, the next select option appears with values pertaining to it. please guys help

0 likes
4 replies
andreasbakir's avatar

Show us what you have build so far. Do you expect us to write your code for you? Give some more information, are you using vue js or something else?

Cronix's avatar

Conceptually, it's pretty simple.

<select id="select-1">
// ... options
</select>

<select id="select-2">
// ... options
</select>
  1. have onChange event on #select-1
  2. get value of #select-1
  3. use ajax to send value to controller, let's say it was "engine"
  4. controller runs query for "engine" and returns data needed for "engine"
  5. in success event of #3, populate #select-2 with new <option>s. You'd just loop over the data returned from the controller to generate new options.
icelander's avatar

this is what I have done. below is my select option. am using Laravel.


 <select class="form-control" id="category" name="category" onchange="return showcategory();">
 @foreach($category as $sel)
 <option value=" {{$sel->id}}"> {{$sel->category}} </option>
 @endforeach 
 </select> 

next is the other select option I want it to be displayed with items pertaining to it when its selected, that is, brake related option when brake option is earlier selected in the initial select option.

 <div class="row" id="description" style="visibility:hidden;">
<select name="description" id="describe" class="form-control-sm form-control">
@foreach($catid as $describe)
<option value="{{$describe->id}} "> {{$describe->problems}} </option>
@endforeach 
</select>

this is the script

<script>
function showcategory(){
var selectBox = document.getElementById('category');
var userInput = selectBox.options[selectBox.selectedIndex].value;
if (userInput == $sel->id){
document.getElementById('description').style.visibility = 'visible';
    }else{
document.getElementById('description').style.visibility = 'hidden';
}
return false;}
</script>

pls assist

Cronix's avatar

Please use code tags. 3 backtics on its own line, followed by code, followed by newline with 3 more backticks

```

code

```

Please or to participate in this conversation.