Search code examples
phpajaxcodeigniterdropdownselected

Fetch the value of the selected options in Drop Down in PHP


I have a dropdown here in my edit view ,I am maintaining the data in my database by "value"(1 and 0) but would like to show it in the dropdown as "Active" and "Deactive")I would like to indicate the selected option , but its not working : here is the view:

<div class="form-group col-md-4" onChange="myNewFunction(this);" >
               <label for="pwd">Status</label>
             <select  class="form-control" id="Status" placeholder="Status" name="Status"  >
              <!-- <option value="">Select Status</option>  -->
                 <option value="1" >Active</option>
                <option value="0" >Deactive</option>
             </select>
             <div class="alert-danger"><?php echo form_error('Status'); ?> </div> 
            </div>

And here is the javascript:

   var conceptName = $('#Status').find(":selected").text();
    //alert(conceptName);  
    var el = document.getElementById('Status');
    var text = el.options[el.selectedIndex].innerHTML;
     ($.trim($("#Status").children("option:selected").text()));

alert(conceptName); => results: the first option of select always

currently I am able to get the innerHTML, but not selected option.


Solution

  • I can't make comments yet but if your edit form is populated from PHP you can do something like this:

    <option value="1"<?php if ($status == 1) echo " selected";?>>Active</option>
    <option value="0"<?php if ($status == 0) echo " selected";?>>Deactive</option>
    

    Replace $status with the variable that contains the status value from your DB.