Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
 }); 
like image 461
Einar Sundgren Avatar asked Jun 25 '13 12:06

Einar Sundgren


People also ask

Which jQuery method triggers or binds a function to the error event of selected elements?

jQuery error() Method The error() method triggers the error event, or attaches a function to run when an error event occurs.

Which jQuery event occurs when add one or more event handlers on the specific child element of matching elements?

delegate() Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


4 Answers

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:

  • .ajax()
  • .get()
  • .load()
  • .post()

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

like image 85
SpYk3HH Avatar answered Nov 08 '22 05:11

SpYk3HH


Why dont you just use:

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

Or am I missing something?

like image 28
reyaner Avatar answered Nov 08 '22 07:11

reyaner


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());
});
like image 28
George Avatar answered Nov 08 '22 06:11

George


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();
});
like image 36
reggaemahn Avatar answered Nov 08 '22 07:11

reggaemahn