当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How to get id of selected option in dropdown?

问题描述:

i want to get the id of selected option in dropdown.

I have a dropdow that displays company names from database. Now I want get the id of that company. How do i do that?

<select required name="org-list" id="org-list" class="form-control">

<option value="">Select</option>

<?php foreach($org as $value) { ?>

<option id="org" value="<?php echo $value['org_name'];?>"><?php echo $value['org_name']; ?></option>

<?php } ?>

</select>

The Model

public function get_organisation()

{

$q = $this->db->select('*')

->from('company')

->get();

return $q->result_array();

}

And in my controller i want the id of selected option from database.

$data = $this->key_m->array_from_post(array('id','org-list','keys'));

$data['keys'] = $license;

var_dump($data);

网友答案:

You should put the organization id in option tag's value. like this

<option value="<?php echo $value['org_id'];?>"><?php echo $value['org_name']; ?></option> 

No need to provide id attribute to each option tag. When you will submit the form value of "org-list" will be selected organization id.

网友答案:

This is the ajax way

$.post(url,{ id : "id value from drop down here" },function(data){
    //This is the call back for success
})

For that one, you need jquery. The is the easiest way to use. Url is where you are posting back to server.

In your server side catch like this

$this->input->post('id')

Because you used "id" in the ajax request. So you have to retrieve it using the field name 'id' . Hope you get it.

网友答案:

You have to provide value for each id attr. for corresponding <option>

<select required  name="org-list"  id="org-list" class="form-control">  
   <option value="">Select</option>    
     <?php foreach($org as $value): ?>              
         <option id="<?php echo $value['org_id'];?>"  value="<?php echo $value['org_name'];?>"><?php echo $value['org_name']; ?></option>
     <?php endforech; ?>
</select>
网友答案:

There are a couple things which you "should" / "could" change. At first I noticed that your ID attribute is "org", Id's are supposed to be unique and yours is not. Though, back to the actual question. You should change your code as follow:

<select required  name="org-list"  id="org-list" class="form-control">  
    <option value="">Select</option>    
      <?php foreach($org as $value): ?>              
           <option id="<?php echo $value['org_id'];?>"  value="<?php echo $value['org_id'];?>"><?php echo $value['org_name']; ?></option>
      <?php endforeach; ?>
</select>

Now in your controller you grab the selected ID like: $this->input->post('org-list').

分享给朋友:
您可能感兴趣的文章:
随机阅读: