4
  • when I select option '2' it opens bootstrap - modal.so the first time it opens modal.now option '2' is already selected. now again I click on option '2'. it doesn't fire any change event so, my bootstrap modal doesn't open.because I wrote logic inside change
    event.
  • so, how can I fire change event on selected option.
rathod151
  • 97
  • 8

3 Answers3

3

Inspite of change event trigger the modal on click event of select option like

$('select option').on('click',function(){
      $("#modelId").modal('show');
});
RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70
  • it seems that option element can not handle the click event. http://stackoverflow.com/questions/28368231/click-event-on-select-option-element-doesnt-work – shuizhongyuemin Feb 28 '17 at 07:17
2

Create a select with a default value option.

<select id="slt">
    <option value="default">Select Something</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

Every time, handle the change event for a not defaultValue option, and then reset the default option to selected.

var $slt = $('#slt'),
    defaultValue = 'default';

function handleChange(e){
    var val = $slt.val();

    // do nothing for defaultValue being selected
    if (val === defaultValue) {
        return;
    }

    // do something else
    console.log(val);

    // reset the value to defaultValue
    $slt.find('option:selected').prop('selected', false);
    $lst.find('option').eq(0).prop('selected', true);
}

$slt.bind('change', handleChange);

But this will make the select always show as "Select Something".

This is a demo about this: http://codepen.io/shuizhongyueming/pen/JWYYLJ


I found another solution for this, which is better than mine.

https://stackoverflow.com/a/12404521/2279763

It use the selectedIndex to reset the selected value on focus, no need for the defaultValue option, and will show the the selected option after click.

This is the demo in the comment: http://fiddle.jshell.net/ecmanaut/335XK/

Community
  • 1
  • 1
shuizhongyuemin
  • 559
  • 5
  • 11
1

You can also use modal function

$('select option').on('click'function(){
    $('modelId').modal('show');
});
Vikram Singh
  • 924
  • 1
  • 9
  • 23