简体   繁体   中英

retrieve id from dropdown/select box codeigniter

Im trying to figure how to retrieve the ID number from a selected value in a dropbox, displaying a list of projects from a table.

At this point what i did was retrieve the value and then search it and get the ID number for that value in the table. Well the field name_project it's "unique" so it's not so bad but i want to retrive the id directly without querying the database offcourse! It's really necessary the use of jquery or javascript to do that?

<?php echo form_open('solucao/inserir',array('class' => 'form-horizontal')); ?>
 <select class="form-control" id="project" name="project">
                            <option>--Choose Project--</option>
                            <?php foreach($projects as $data):?> 
                            <option><?php echo $data->name_project?></option>
                            <?php endforeach;?>  
                            </select>
<?php form_close(); ?>

Note: $data is an array wich contains the ID number!

Thank you!

Hope you have project_id and project_name as field names in your project table

In model:

function getProjectArr()
{
    $res =  $this->db->get("project");
    $ret_arr = array();
    if($res-<num_rows()>0)
    {
       foreach($res->result() as $r)
       {
          $ret_arr[$r->project_id] = $r->project_name;
       }
    } 
    return $ret_arr;
}

In your controller,

$data["project_list"] = $this->MODEL_NAME->getProjectArr();

In View file

echo form_dropdown("project",$project_list,'','id="project" class="form-control"');

You will get dropdown with ids as option value and names as option text.

When you will get the id on select or options tag.

Then get the id of selected option you can use something like this.

document.getElementById('project').addEventListener('change', selectId);
function selectId(){
    alert(this.options[this.selectedIndex].id);
}

Demo

OR

Get the id of select tag then you can use

document.getElementById('project').addEventListener('change', selectId);
function selectId(){
    alert(this.id);
}

Demo2

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