Muhammad Irfan Sumra
Muhammad Irfan Sumra

Reputation: 15

JQuery change() function is not working when there is only one option in select list

I am trying to get data using jquery from a select list which is populated dynamically. Jquery change() functions works well when there are many options in the list but it doesn't fire when there is only one option. My code is below

<?php
    $res=$db->SelectData("amgusers");

    if (mysqli_num_rows($res) > 0) {    
        while($row = mysqli_fetch_array($res))
        {
            echo'<option value="'.$row['u_id'].'">'.$row['u_username'].'</option>';
        }
    }                           
?>

<script>    
    $("#uname").change(function()
    {
        alert($("#uname option:selected").text());
    });
</script>

Upvotes: 0

Views: 1369

Answers (2)

Monica Acha
Monica Acha

Reputation: 1086

If there is only one item in the dropdown, it wont work.

You can try onClick() instead.

Otherwise make an option as --select-- on the top of select box. Ignore that accordingly in your JavaScript.

Upvotes: 2

Mark Schultheiss
Mark Schultheiss

Reputation: 34217

You have a few options. Add more events or set a default and trigger it. OR combine that. You might also set the default to the first either in markup (selected) or force ONLY if one.

Two events (seems to not be great if you only have one, or do not change it)

$("#uname").on('change click', function() {
  if ($(this).find('option').length === 1 && !$(this).find('option:selected').length) {
    $(this).find('option').prop("selected", true);
  }
  alert($(this).find("option:selected").text() + " : " + $(this).val());
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="uname">
  <option value="me">My Option</option>
</select>

Better perhaps, I find the multiple events is probably NOT great since you only want it on a change SO I opt for that. (and "click" just seems to not be suitable here)

$("#uname").on('change', function() {
  if ($(this).find('option').length === 1 && !$(this).find('option:selected').length) {
    $(this).find('option').prop("selected", true);
  }
  alert($(this).find("option:selected").text() + " : " + $(this).val());
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="uname">
  <option value="me">My Option</option>
</select>

Note this second set of code also works when you have an "empty" first option value but you might then also need to make the first one NOT select-able or otherwise handle that condition when it is selected.

Upvotes: 1

Related Questions