Detect with JQuery when a select changes
Asked Answered
C

2

42

I have a Jqgrid which dynamically generates selects like this:

    <select id="won" style="width: 65px;">
       <option value="">-WON?</option>
       <option value="1" selected>Bet1</option>
       <option value="2" >Bet2</option>
       <option value="3" >Bet3</option>
    </select>

Each one have a different selected option. I would like to detect when one select changes so I can save it in my database.

I'm trying with:

         $('#won').change(function(){
               alert("PROBANDO");
          });

But is not working at all.

Contractile answered 22/10, 2013 at 21:16 Comment(0)
W
98

The problem is that the select are created dynamically, then you need to use .on()

try this:

         $(document).on('change','#won',function(){
               alert("PROBANDO");
          });
Wolf answered 22/10, 2013 at 21:17 Comment(7)
How could I detect which won is changing? I should name them different?Contractile
usually inside html id are unique! is very important this rule. if you can create more select with different id like won1, won2. If you can't use classes like won1, won2 but I really advise you to have unique id inside your html @ContractileWolf
$(this).find("option:selected").attr('value') tells you the new "won value" if it is what you are looking for ...Minerva
what are you talking about? OP ask which of the select are changed not the current selected option @CorinneKublerWolf
I will :) How can I call this function with dinamically "wons" (won320, won896, won99) ?? var x = 0; $(document).on('change','#won'+x,function(){ alert("PROBANDO"); });Contractile
you can do this: $(document).on('change','[id^="won"]',function(){ alert("PROBANDO"); }); or something similar, it would be that find changing of input that id starts with string "won" @ContractileWolf
oups so $(this) will give the select which changed isn't it ?Minerva
M
37

This should work, be sure you did not forget $(document).ready(function() {

$(document).ready(function() {  
    $('#won').change(function(){
        alert( $(this).find("option:selected").attr('value') );       
    });
 });
Minerva answered 22/10, 2013 at 21:20 Comment(2)
Found this most usefullBowfin
this is waiting for the document to be ready, but if #won is generated dynamically this will fail. The correct answer is to listen for events at a stable, non generated html node, and check the event came from the correct child node, in this case the stable node is "document" and "#won" is the child.Sanburn

© 2022 - 2024 — McMap. All rights reserved.