Domanda

I am trying to handle a change event for a dropdrown which looks like this:

 <div>
    <select id="serviceLine">
      <option selected="selected">--Select Option--</option>
      <option>Integration</option>
      <option>BPM</option>
      <option>GWT</option>
      <option>Other</option>
    </select>
 </div>

Now,I want to add a textarea when the user selects option "Others". The jQuery looks like this:

function otherHandler(){
       $(this).siblings("textarea").remove();
       if($(this).val()=="Other"){

              var textbox="<textarea rows='3'></textarea>";
              $(this).parent().append(textbox);
       }

}

$("#serviceLine").on("change",function(){otherHandler()});

This doesn't work, because in otherHandler() $(this) contains the reference of the entire window and not just the dropbox.

However if I change my jQuery to this, it works fine:-

function otherHandler(that){
       $(that).siblings("textarea").remove();
       if($(that).val()=="Other"){

              var textbox="<textarea id='slOther'rows='3'></textarea>";
              $(that).parent().append(textbox);
       }

}


$("#serviceLine").on("change",function(){otherHandler(this)});

My question is why didn't it work in the first case, why do we have to pass the reference explicitly? Am I missing something major here?

È stato utile?

Soluzione 2

Raed this keyword

$("#serviceLine").on("change",function(){
    //this --> is local to the function block here you cannot use it outside
});

$("#serviceLine").on("change",function(){otherHandler(this)});
                                                      //^

Here you pass the reference of this to the function so it works


Better use

$("#serviceLine").on("change", otherHandler);
                                //^ function name

Altri suggerimenti

In your first case it didn't worked as this is for defined for the event handler.

$("#serviceLine").on("change",function(){
    // this is accessible here in event handler not in the otherHandler function call
     otherHandler();
});

You should have directly passed the reference of function

$("#serviceLine").on("change", otherHandler);

If you wish you can use .apply(this)

function otherHandler(){
       $(this).siblings("textarea").remove();
       if($(this).val()=="Other"){

              var textbox="<textarea rows='3'></textarea>";
              $(this).parent().append(textbox);
       }

}

$("#serviceLine").on("change",function(){
   otherHandler.apply(this);
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top