JQuery event handler when select element is loaded

Is there an event handler to use in JQuery when a DOM select element has finished loading? This is what I want to achieve. It is working with other events except 'load'.

This piece of code is loaded in the head.

$(document).on('load', 'select', function(){
    var currentSelectVal = $(this).val();
    alert(currentSelectVal);
    } );

The question was badly formed earlier. I need to attach the event handler to all select elements, both present when the document is loaded and dynamically created later.

They are loaded from a JQuery Post to a php-page. Similar to this:

$.post("./user_functions.php", 
{reason: "get_users", userID: uID}) 
.done(function(data) { $("#userSelector").html(data);
 }); 

Answers:

Answer

I think we're all confused. But a quick break down of your options.
After an update made to the Question, it looks like the answer you might seek is my last example. Please consider all other information as well though, as it might help you determine a better process for your "End Goal".

First, You have the DOM Load event as pointed out in another answer. This will trigger when the page is finished loading and should always be your first call in HEAD JavaScript. to learn more, please see this API Documentation.

Example

$(document).ready(function () {
    alert($('select').val());
})
/*  |OR|    */
$(function() {
    alert($('select').val());
})

Then you have Events you can attach to the Select Element, such as "change", "keyup", "keydown", etc... The usual event bindings are on "change" and "keyup" as these 2 are the most common end events taking action in which the user expects "change". To learn more please read about jQuery's .delegate() (out-dated ver 1.6 and below only), .on(), .change(), and .keyup().

Example

$(document).on('change keyup', 'select', function(e) {
    var currentSelectVal = $(this).val();
    alert(currentSelectVal);
}) 

Now delegating the change event to the document is not "necessary", however, it can really save headache down the road. Delegating allow future Elements (stuff not loaded on DOM Load event), that meet the Selector qualifications (exp. 'select', '#elementID', or '.element-class') to automatically have these event methods assigned to them.

However, if you know this is not going to be an issue, then you can use event names as jQuery Element Object Methods with a little shorter code.

Example

$('select').change(function(e) {
    var currentSelectVal = $(this).val();
    alert(currentSelectVal);
}) 

On a final note, there is also the "success" and "complete" events that take place during some Ajax call. All jQuery Ajax methods have these 2 events in one way or another. These events allow you to perform action after the Ajax call is complete.

For example, if you wanted to get the value of a select box AFTER and Ajax call was made.

Example

$.ajax({
    url: 'http://www.mysite.com/ajax.php',
    succuess: function(data) {
        alert($("select#MyID").val());
    }
})
/*  |OR|    */
$.post("example.php", function() { alert("success"); })
.done(function() { alert($("select#MyID").val()); })
/*  |OR|    */
$("#element").load("example.php", function(response, status, xhr) {
    alert($("select#MyID").val());
});

More reading:

Something else to keep in mind, all jQuery Ajax methods (like .get, .post) are just shorthand versions of $.ajax({ /* options|callbacks */ })!

Answer

Why dont you just use:

$(document).ready(function () {
   //Loaded...
});

Or am I missing something?

Answer

For your dynamic selects you can put the alert in the callback.

In your .post() callback function, try this:

.done(function(data) {
    data = $(data);
    alert(data.find("select").val());
});
Answer

Ok, correct me if I understand this wrong. So you want to do something with the selects when the document is loaded and also after you get some fresh data via an ajax call. Here is how you could accomplish this.

First do it when the document loads, so,

<script>
//This is the function that does what you want to do with the select lists
function alterSelects(){
 //Your code here
}
  $(function(){
      $("select").each(function(){
           alterSelects();
      });
  });
</script>

Now everytime you have an ajax request the ajaxSend and ajaxComplete functions are called. So, add this after the above:

$(document).ajaxSend(function () {
}).ajaxComplete(function () {
    alterSelects();
});

The above code will fire as soon as the request is complete. But I think you probably want to do it after you do something with the results you get back from the ajax call. You'll have to do it in your $.post like this:

$.post("yourLink", "parameters to send", function(result){
    // Do your stuff here
    alterSelects();
});
Answer

Do you want all Selects to be checked when the User-Select is loaded, or just the User-Select?...

$.post("./user_functions.php", {reason: "get_users", userID: uID}).done(function(data) {  
    $("#userSelector").html(data);
    //Then this:
    var currentSelectVal = $("#userSelector").val();
    alert(currentSelectVal);
});
Answer

If your select elements are dynamically loaded, why not add the event handler after you process the response?

e.g. for ajax

$.ajax({
  ...
  success: function(response) {
   //do stuff 
   //add the select elements from response to the DOM 
   //addMyEventHandlerForNewSelect();

   //or

   //select the new select elements from response
   //add event handling on selected new elements
  },
  ...
});
Answer

My solution is a little similar to the posters above but to use the observer (pubsub) pattern. You can google for various pub sub libraries out there or you could use jQuery's custom events. The idea is to subscribe to a topic / custom event and run the function that attach the event. Of course, it will be best to filter out those elements that have been initialize before. I havent test the following codes but hopefully you get the idea.

function attachEventsToSelect(html) {
    if (!html) { // html is undefined, we loop through the entire DOM we have currently
        $('select').doSomething();
    } else {
        $(html).find('select').doSomething(); // Only apply to the newly added HTML DOM
    }
}

$(window).on('HTML.Inserted', attachEventsToSelect);

// On your ajax call
$.ajax({
    success: function(htmlResponse) {
        $(window).trigger('HTML.Inserted', htmlResponse);
    }
});

// On your DOM ready event
$(function() {
    $(window).trigger('HTML.Inserted'); // For the current set of HTML
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.