Ajay Krishna Dutta
Ajay Krishna Dutta

Reputation: 770

change() function not working with selected value

If I select the selected option text " A " the change() function is not working. But if I select some other like B,C its work fine and after that if I select the A its work nicely.Why its not working in beginning.Is it possible to triggered the function . Please help

$('#type').change(function() {
  var val = $('#type option:selected ').val();
  alert(val);
})

$(function() {
  $('#type').val('1');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="type">
  <option >--Select--</option>
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>

Upvotes: 0

Views: 311

Answers (1)

Asons
Asons

Reputation: 87292

One possible option is to keep track on whether the select is open, and if, and someone also clicked on it, you call a function

In addition, you save the current value in an attribute and then compare in the mouseup event if they are the same, and if, you trigger the change event manually, as the change event won't fire by itself since the user clicked the same option.

$(document).ready(function() {

  var isOpen = false;

  // Init any selection
  $('#type').attr('data-val', $('#type').val());

  $('#type').change(function() {
    selectWasClicked($(this).val());
  })

  $('#type').mouseup(function() {
    if (!(isOpen)) {
      isOpen = true;
      return;
    }
    isOpen = false;
    if ($(this).attr('data-val') == $(this).val()) {
      $(this).trigger("change");
    }
    $(this).attr('data-val', $(this).val());
  })

  $('#type').blur(function() {
    isOpen = false;
  })

  function selectWasClicked(val) {
    console.log('someone clicked on the select value: ', val);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="type">
  <option >--Select--</option>
  <option value="1" selected>A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>

Upvotes: 1

Related Questions