Jquery execute onchange event on onload

I have a function that on change event run the post actions.

$("select#marca").change(function(){
    var marca = $("select#marca option:selected").attr('value');
    $("select#modello").html(attendere);
$.post("select.php", {id_marca:marca}, function(data){
        $("select#modello").html(data);
    });
});

I would like to perform this function onload event. Is it possible? Is there a good way to do this?

Answers:

Answer

Just put it in a function, then call it on document ready too, like so:

$(function () {
    yourFunction(); //this calls it on load
    $("select#marca").change(yourFunction);
});

function yourFunction() {
    var marca = $("select#marca option:selected").attr('value');
    $("select#modello").html(attendere);
    $.post("select.php", {id_marca:marca}, function(data){
        $("select#modello").html(data);
    });
}

Or just invoke change on page load?

$(function () {
    $("select#marca").change();
});
Answer

Really simple way it to just chain another .change() event to the end of your on change function like this:

$("#yourElement").change(function(){
   // your code here
}).change(); // automatically execute the on change function you just wrote
Answer

If you add .change() to the end it will be called straight away after being bound:

$(function() { 
    $("select#marca").change(function(){
        var marca = $("select#marca option:selected").attr('value');
        $("select#modello").html(attendere);
    $.post("select.php", {id_marca:marca}, function(data){
            $("select#modello").html(data);
        });
    }).change(); // Add .change() here
});

Or change the callback to an actual function and call that:

function marcaChange(){
    var marca = $("select#marca option:selected").attr('value');
    $("select#modello").html(attendere);
$.post("select.php", {id_marca:marca}, function(data){
        $("select#modello").html(data);
    });
}

$(function() { 
    $("select#marca").change(marcaChange);
    marcaChange();
});
Answer

To call onload, you can try jQuery:

 $(document).ready(function(){
 onchange();// onload it will call the function
     });

Write your onchange function like this, so this will be called when onchange occurs,

function onchange(){
    var marca = $("select#marca option:selected").attr('value');
    $("select#modello").html(attendere);
    $.post("select.php", {id_marca:marca}, function(data){
    $("select#modello").html(data);
});
Answer

The other way to do

 $("select#marca").val('your_value').trigger('change');
Answer

this is working for me.

 $(function () {
    $('#checkboxId').on('change', hideShowfunction).trigger('change');
});

function hideShowfunction(){
//handle your checkbox check/uncheck logic here
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.