5

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);
 }); 
6
  • Is this input loaded on document load?
    – George
    Jun 25, 2013 at 12:50
  • When it's loaded? Like, there is the dom load? what do you mean, when select is loaded? You mean changed?
    – SpYk3HH
    Jun 25, 2013 at 12:50
  • Tell us how they are dynamically loaded. AJAX? Show the script here.
    – George
    Jun 25, 2013 at 12:56
  • Edited and explained. Hope my question gets clearer. Jun 25, 2013 at 13:01
  • I think I fully answered all of your question. Let me know if there's more I can explain. The links I included should also prove beneficial. Good Luck!
    – SpYk3HH
    Jun 25, 2013 at 13:04

7 Answers 7

9

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 */ })!

7
  • 1
    Thanks for taking you time. And I might be the most confused here. I fully understand what you say, but my original problem remains: I want the browser to do some task whenever a select element is dynamically loaded. Not when the entire document is first loaded. And $(document).ready() will only fire when the document first loads. Jun 25, 2013 at 13:20
  • @Einar Not sure if you saw this answer before or after, but that's why I updated the end of my answer. I talk exactly about making changes after a "POST" or "GET" of some sort. What you need to look at is jQuery's success functions on their Ajax methods.
    – SpYk3HH
    Jun 25, 2013 at 13:24
  • You comment loaed while I was writing. I might need to do some more reading on those functions. But I realised that elements that are not registered for event handlers before they are loaded is not accesible through any ordinary Javascript DOM manipulation. Jun 25, 2013 at 13:27
  • 1
    @Einar I should have also mentioned, and I just added this to my answer, but, "Something else to keep in mind, all jQuery Ajax methods (like .get, .post) are just shorthand versions of $.ajax({ /* options|callbacks */ })!"
    – SpYk3HH
    Jun 25, 2013 at 13:35
  • 1
    You answered the s**t out of that question
    – George
    Jun 25, 2013 at 13:47
3

Why dont you just use:

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

Or am I missing something?

3
  • The question was badly fored. I need to attach the event handler to all select elements, also the ones that are dynamically loaded. I will edit my question. Jun 25, 2013 at 12:51
  • How are they dynamically loaded?
    – George
    Jun 25, 2013 at 12:54
  • They are mostly loaded from a jquery Post to a php-page. Like this: $.post("./user_functions.php", {reason: "get_users", userID: uID}) .done(function(data) { $("#userSelector").html(data);}); Jun 25, 2013 at 12:56
1

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());
});
1

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();
});
0

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);
});
1
  • Basically only the #userSelector. But that is not a big issue right now. As long as I can fire an event when any of them are loaded I will be happy. Jun 25, 2013 at 13:31
0

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
  },
  ...
});
3
  • That way it will only work if the elements are present in the original DOM. Not if they are added afterwards. Jun 25, 2013 at 13:04
  • For elements that are already on the DOM (on load of a page), you can use $(document).ready(function() { //on change event, for example $('.mySelectDOMselector').on('change', function() { doMyEvent(); }) }) For dynamically loaded elements, you can add the assignment of the event handler on the success callback of your ajax-post call. Jun 25, 2013 at 13:26
  • I know. And my original question was if there is such and event handler that fires when the element is loaded dynamically, not on change or on mouseover. But I might have formed it a bit fuzzy. Jun 25, 2013 at 13:29
0

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
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.