views:

35

answers:

3

Hey guys,

I want to use the argument I pass (this) in a JS function and treat it as an jQuery variable. Example:

<script>    
function useMe(obj){
  $(obj).val();
  ...
  ... 
  ...
}
</script>


<select id="selectid" onChange="useMe(this)">
    <option>......</option>
</select>

Is there a possibility to treat the passed argument as a jQuery element?

Btw. I need to do it this way, because the select-element isn't created on load. The select element will be created later asynchronously.

So, this won't work:

$("select").each(function (i){
    var select_id = $(this).attr("id");                
    $(this).change(function(e){  

because it doesn't exist yet.

Thanks for your help.

A: 

If the element doesn't exist at the document load it means that it is later added maybe by an AJAX call. If this is the case just put the change handle registration in the success callback.

$.ajax({
    url: '/somescript',
    success: function() {
        // some code that injects the select into the DOM
        // ...
        $("select").each(function(i) {
            var select_id = $(this).attr("id");                
            $(this).change(function(e) {
                // ...
            });
        });
    }
});
Darin Dimitrov
cool thanks. I still got one question. Where do i need to insert this code? Into the file which loads the file or into the loaded (ajax) file?
Kel
you should already have this code somewhere. the only code you need to insert is `$("select) ...` within the function called on success
jigfox
+2  A: 

If your element isn't created on load, and loaded asynchronously instead you can bind the change event like this:

$('select').live('change',function(){
  // ...
});

This will bind the defined function to the change event on every existing and on every new select item.

Update: You need at least jQuery 1.4.1 for this

jigfox
awesome! it works thank you
Kel
you're welcome!
jigfox
does it work for IE6?UPDATE:found this: http://stackoverflow.com/questions/1451760/jquery-live-change-in-not-working-in-ie6-ie7
Kel
A: 

If you do choose to stick with your onchange attribute (which I would advise against), just use:

<script>    
function useMe($obj){
  $obj.val();
  ...
  ... 
  ...
}
</script>

<select id="selectid" onChange="useMe($(this))">
    <option>......</option>
</select>
Eric