Home » Jquery » jquery – On select change get select data-id attribute value

jquery – On select change get select data-id attribute value

Posted by: admin February 22, 2020 Leave a comment

Questions:

I am trying this Code That is my select value

<select class="select2 lang_change">
                            <option selected value="english" data-id="" <?php
                            if (isset($_SESSION['lang'])) {
                                set_selected($_SESSION['lang'], 'english');
                            }
                            ?> >English</option>
                            <!--<option value="2">Chinese</option>-->
                            <option value="spanish" data-id="es" <?php
                            if (isset($_SESSION['lang'])) {
                                set_selected($_SESSION['lang'], 'spanish');
                            }
                            ?>>Spanish</option>
                            <!--<option value="4">Hindi</option>-->
                            <!--<option value="5">Filipino</option>-->
                        </select>

That is my Jquery Or ajax value

$('.lang_change').on('change', function () {
 var dataid = $(".lang_change option:selected").attr('data-id');    
 var val = this.value;
            $.ajax({
                url: "<?php echo base_url('lang_change/'); ?>" + "?"+val+"&"+dataid,
                type: "GET",
                cache: false,
                dataType: "JSON",
                success: function (dataResult) {
                    if (dataResult.statusCode == 200)
                    {
                        location.reload();
                    }
                }
            });
        });
    </script>

That is my code how can i get onchange get select data-id attribute value
Help

How to&Answer:

I have corrected your script, and its getting data-id.

$('.lang_change').on('change', function() {
  var dataid = $(".lang_change option:selected").attr('data-id');
  alert(dataid)
  var val = this.value;
  $.ajax({
    url: "<?php echo base_url('lang_change/'); ?>" + val,
    type: "GET",
    cache: false,
    dataType: "JSON",
    success: function(dataResult) {
      if (dataResult.statusCode == 200) {
        location.reload();
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="select2 lang_change">
  <option selected value="english" data-id="es" <?php if (isset($_SESSION[ 'lang'])) { set_selected($_SESSION[ 'lang'], 'english'); } ?> >English</option>
  <!--<option value="2">Chinese</option>-->
  <option value="spanish" data-id="spanish" <?php if (isset($_SESSION[ 'lang'])) { set_selected($_SESSION[ 'lang'], 'spanish'); } ?>>Spanish</option>
  <!--<option value="4">Hindi</option>-->
  <!--<option value="5">Filipino</option>-->
</select>