简体   繁体   中英

Display related data from database based on dropdown selection JavaScript

In my task I want to select one name from drop down. Then I want to print the technology related to that name in other div tag. I don't know how to do this. I successfully get data from data base for dropdown option. Here is my code.

candidate name:
<select name="candidate_id" class="form-control" id="can_name" value="<?php echo set_value('candidate_id');?>"palceholder="candidate full name" required>
    <option></option>
    <?php foreach ($candidate as $r): ?>
        <option value="<?php echo $r->candidate_id; ?>"><?php echo $r->candidate_name." "; ?></option>
    <?php endforeach; ?>
</select>
</select>

<div class="error"><?php echo form_error("candidate_name");?></div><br>
<div></div><br> <!-- here I want to print technology related to canididate name -->

let's use the jQuery library, as this will simplify the syntax of what you want to do considerably.

You include it in your page like this:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

This will pull in the most recent minified version of the 1.x branch of the library.

Then you need a select. I was about to say, let's use below ex.

Let's use a select anyway, you can change it if it isn't correct:

 <label for="meetingPlace">Meeting place: </label>  
   <select id="meetingPlace">
   <option>Please select</option>
   <option>Buckingham Palace</option>
   <option>The White House</option>
   <option>Mount Everest</option>
 </select>

With that in place you need to hook into the select's on change event. you can do this in your JavaScript:

 $("#meetingPlace").on("change", function(){
 // This code will fire every time the user selects something
 })

All this does is select the element with an id of "#meetingPlace" and declare an anonymous function which should be run every time the user selects something different.

As a final step for this post, let's have the JS output what the user selected to the page.

Create a div with an id of "results":

  <div id="results"></div>

Then within the onchange callback add the following code:

var selected = $(this).val();
$("#results").html("You selected: " + selected);

What this does is assign the value of the selected option element to a variable, then set the innerHTML of the results accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM