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?
otherHandlerwrapped in an anonymous function for some reason, like there's other code before or after it, then you can obtain the properthisvalue inotherHandler()by using.call()or.apply()to invoke the function.otherHandler.call(this)