user606336
user606336

Reputation: 101

Execute jQuery function on load and change

I have a select field in a form, and wish to execute some jQuery when the field is changed or when the page is reloaded on form submit.

<select name="emp_status_id" class="emp-status-id" >
    <option value=""></option>
    <option value="1">Full-Time Employment</option>
    <option value="2">Part-Time Employment</option>
    <option value="3">Casual</option>
    <option value="4">Self Employed</option>
</select>

My jQuery is below

function employmentGroups(id){ 
    var emp_status_id = id.val();
    // Do more stuff here
};

$( ".emp-status-id" ).change(function() {
    employmentGroups($(this));
});

Not: I am passing $(this) into the function rather than getting $(this) inside the function for another reason which isn't relevant to the current question.

This works perfectly well on change.

I would also like to execute the function on page load,

My problem is that I do not understand which jQuery method to use to execute this function on load.

I have tried this...

$( ".emp-status-id" ).ready(function() {
    employmentGroups($(this));
});

However this does not work.

Upvotes: 1

Views: 2099

Answers (3)

Amir Fawzy
Amir Fawzy

Reputation: 468

there's two ways to do such a thing like this

1- using load() but this will fire whatever the code inside every time page reload even when the use open the page for the first time

$(window).load(function() {
  // do whatever you want
});

2- using built-in PerformanceNavigation interface ... i didn't test such a case to use it but it exactly for detecting navigation behavior

if (performance.navigation.type === 1) {
  console.log('page reloaded');
}

or (is the same as above but with different syntax)

if (performance.navigation.type === PerformanceNavigation.TYPE_RELOAD){
  console.log('page reloaded');
}

for further reading W3 and MDN

Upvotes: 0

Evgeny A. Mamonov
Evgeny A. Mamonov

Reputation: 1886

Better way to access this selectbox value by id. Here is working code:

<select id="emp_status_id" name="emp_status_id" class="emp-status-id" >
    <option value=""></option>
    <option value="1">Full-Time Employment</option>
    <option value="2">Part-Time Employment</option>
    <option value="3">Casual</option>
    <option value="4">Self Employed</option>
</select>

function employmentGroups(selector_id){ 
    var emp_status_id = $(selector_id).val();
    // Do more stuff here
};

// on page loaded
$(function() {

    // set onchange handler       
    $("#emp-status-id").change(function() {
        employmentGroups('#emp-status-id');
    });

    // just execute 
    employmentGroups('#emp-status-id');
});

Upvotes: 2

Munkhdelger Tumenbayar
Munkhdelger Tumenbayar

Reputation: 1874

$(document).ready(function(){ employmentGroups($( ".emp-status-id" )); })

Looking for this?

Upvotes: 1

Related Questions