theveil
theveil

Reputation: 77

jquery get data attributes of select2 inside while loop php

I have been reviewing similar questions related to select2 data attributes, but couldn't find what I'm looking for. I have been taking time on this.

Basically I have a select2 dropdown inside a while loop which fetch values from sql database. I need to add an additional data attribute and when an option is selected, I need to display the selected data attributed in the input field. My code goes as below

 <select class="select2-dropdown form-control" tabindex="-1" id="user" name="user">
    <option value="">Select User</option>
    <?php
    $fetchuser = mysqli_query($link,"SELECT * FROM user ORDER BY name ASC") or die(mysql_error());
    while($row=mysqli_fetch_assoc($fetchuser))
    {
        $id = $row["id"];
        $name  = $row["name"];
        $status = $row["status"];
    ?>
     <option value="<?php echo $id; ?>" data-status="<?php echo $status; ?>"><?php echo $name; ?></option>

    <?php } ?>
</select>
<input id="status" />

My JS:

<script type=text/javascript>
    $('#user').on('select2:selecting', function() {
        var status=$(this).find(":selected").data("status");
        $('#status').val(status); 
    });
</script>

I'm only getting random status (not corresponding to the selected), and some options status is not displayed when selection is changed.

Could anyone suggest where i have made the mistake.

Thank you in advance.

Upvotes: 0

Views: 2880

Answers (2)

Amit Sharma
Amit Sharma

Reputation: 1795

I think it will change function that you need to use

 $('#user').on('change', function() {
    var status= $(this).find(":selected").data("status");
    $('#status').val(status); 
});

Upvotes: 2

Igris
Igris

Reputation: 76

Your code is so weird for me. Try this:

  $('select').on('change', function() {
    var status=$(this).find(":selected").data("status");
    $('#status').val(status);
  });

Upvotes: 3

Related Questions