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

Purpose: I am creating a dropdown using Ajax in JQuery to fetch data from a database and submit to html with html format.

Problem: I am unable to use any selector inside my dropdown which is after the Ajax response.

Description: I used PHP to select a City from the database and echo with a select ( <selection></selectio>

) tag to take a snapshot and use #location to send the data from the Ajax tag to a div to show to the user in the browser. My job is dumping very well. But I cant #testing selector to make an alert after user changes any value of each dropdown.

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 clicks on each dropdown (all internal JS document)

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

      

Here is the div tag

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

      

+3


source to share


2 answers


For dynamically added elements in the DOM you need $(document)

as shown below:



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

      

+2


source


$.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
        //    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
});

      



+1


source







All Articles