javascriptjquerycombobox

How to fire onchange event of combobox?


I have a combobox, How to fire onchange event of the combobox and get a selected value from it.

Here is the Code what i did till now :

<select name="g1" id="select_g1">
        <option value="one">one</option>
        <option value="two">two</option>
        <option value="three">three</option>
    </select>

    <script>
        $(document).ready(function(){

            $("select_g1").change(function(){
                alert("Handled"); // alert is not fired up ...
            });
        });

    </script>

EDIT : What if i have more than one combobox :

<select name="g2">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>

Also disable the value selected in combobox g1 in combobox g2.

Could anyone please tell me what is wrong with the code.


Solution

  • Rather than trying to use the .change event, please try to use the .on event.

    You can try to use it as such:

    $('#select_g1').on('change', function (e) {
        var optionSelected = $("option:selected", this);
        var valueSelected = this.value;
        alert(valueSelected);
    });
    

    See this here -> http://jsfiddle.net/ocrozmkn/

    EDIT :

    With respect to your edited question, you can try the following jQuery :

    $('select').on('change', function (e) {
        $('select option').prop('disabled', false);
        var optionSelected = $("option:selected", this);
        var valueSelected = this.value;    
        alert(valueSelected);
        $("select option:contains('" + valueSelected + "')").attr("disabled","disabled");
    });
    

    See this here ->http://jsfiddle.net/ocrozmkn/1/

    Demo for multiple comboboxes

    See here -> http://jsfiddle.net/ocrozmkn/6/

    Hope this helps!!!