DMS-KH
DMS-KH

Reputation: 2787

How to get value from select tag after Ajax response as html format?

Purpose: I'm creating a drop down using Ajax in Jquery to select data from database and send to html with html format.

Issue: I can't using any selector inside of my drop down which after Ajax respond.

Description: I used PHP to select City from database and echo with select tag (<selection></selectio>) to make a drop down and use #location to send data from Ajax to div tag to showing to user in browser.My drop down work very well But I can't used #testing selector to make alert after user change any value of each list of drop down.

PHP function

public function select_cat($table = FALSE, $where = FALSE) {

        $this->db->select('*');
        $this->db->from($table);
        if ($where) {
            $this->db->where($where);
        }
        $q = $this->db->get();
        if ($q->num_rows() > 0) {
            echo '<select id="testing" name="p_locat" class="form-control" id="p_locat">';
            foreach ($q->result() as $row) {
                echo "<option value=" . $row->l_id . ">" . $row->city . "</option>";
            }
            echo '</select>';
        } else {
            return FALSE;
        }
    }

Here is My Ajax

   $(document).ready(function(){
    $.ajax({
      url: "<?php echo base_url('ads/get_locat'); ?>",
      data: {'<?PHP echo $this->security->get_csrf_token_name(); ?>': '<?PHP echo $this->security->get_csrf_hash(); ?>'},
      dataType: "html",
      cache: false,
      success: function (data) {
      console.log(data);
      $("#location").html(data);
     }
    });
   })

Call Alert() after user click on each drop down (All JS inside document)

$("#testing").on('change',function(){
        alert($("#p_locat"));
    })

Here is div tag

<div id="location"></div>

Upvotes: 3

Views: 6879

Answers (2)

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

For dynamically added elements to the DOM you need to $(document) as below:

$(document).on('change',"select#testing",function(){
 alert($('#testing option:selected').val());
//Write stuffs
});

Upvotes: 2

Tushar
Tushar

Reputation: 87203

$.ajax({
    url: "<?php echo base_url('ads/get_locat'); ?>",
    data: {
        '<?PHP echo $this->security->get_csrf_token_name(); ?>': '<?PHP echo $this->security->get_csrf_hash(); ?>'
    },
    dataType: "html",
    cache: false,
    success: function (data) {
        console.log(data);
        $("#location").html(data); // Throw HTML in DOM

        alert($('#testing option:selected').val()); // Get the selected value
        //    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
});

Upvotes: 1

Related Questions