简体   繁体   中英

Change text from a while loop dropdown list from a database

I would like to know how I can change the text to based on the dropdown list. An example of it is that I would select the name in the dropdown, and having the text in the text area to be changed accordingly. I have done a some research so far and needs to use ajax.

The following are my codes:

<label for="CandidateName">Candidate Name:</label> 
<select name="candidateName">

<?php
if ($shortlistedCandidates > 0) { // Just to count and get how many data from database.

  while ($row = mysqli_fetch_array($result)) {

     $cid = $row['candidate_id'];
     $firstName = $row['first_name'];
     $lastName = $row['last_name'];
     $combined = "$firstName $lastName";

     echo "<option value='$cid'>" . $combined . "</option>";
    }
} else {
     echo "<option>No candidates to be shortlisted</option>";
  }
}
?>
</select>

This needs to be done with more than one file to make it asynchronous. So, you have the select element and the option s produced with PHP. Use onchange in the select element to triggers another PHP document to load the result in an other div . I'll give an example with the jQuery library.

HTML:

<select id='candidate' onchange='get_candidate(this.value);'>
 options generated with PHP
</select>
<div id='candidate_result'></div>

Javascript (put this in the html document)

<script>
function get_candidate(id) {
    $( "#cart" ).load( "candidate.php?id="+id );
</script>

PHP file

<?php 
    $candidate_id = $_GET['id'];
    // do you sql query with the $candidate_id en echo it!
?>

Didn't test this code, but try to follow what happens here.

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