Himanshu Joshi
Himanshu Joshi

Reputation: 292

How to set on change as a default on page load jquery?

I have created a on change method for a select box of my project. On selecting particular option it is basically showing and hiding a div which is perfectly working fine. Now, my problem is when first time page is loading this show and hide not working for first default section of form. Can I make this onchange function also working when page load first time.

$('.contact-form').on('change', (e) => {
    var selectedId = $(e.currentTarget).val();
    var listofforms = $("#discount").data("display-for").split(",");
    if (listofforms.indexOf(selectedId) !== -1) {
        $("#discount").collapse('show');
    }
    else {
        $("#discount").collapse('hide');
    }
});

Upvotes: 1

Views: 799

Answers (2)

palaѕн
palaѕн

Reputation: 73906

Is it possible can I make my on change trigger on page load

Yes, you will just need to change your on change event from e.currentTarget to this as on page load e.currentTarget will be null, but this always points to the current element like:

$('.contact-form').on('change', function() {
  var selectedId = $(this).val();
  // Your other logic here
});

and to trigger this change event on page load, simply add .change() at last like:

$('.contact-form').on('change', function() {
  var selectedId = $(this).val();
  // Your other logic here
}).change();   //<---- here

Upvotes: 0

Shiladitya
Shiladitya

Reputation: 12181

Here you go with a solution

function changeMethod(selectedId) {
  var listofforms = $("#discount").data("display-for").split(",");
  if (listofforms.indexOf(selectedId) !== -1) {
    $("#discount").collapse('show');
  }
  else {
    $("#discount").collapse('hide');
  }
}

changeMethod($('.contact-form').val())

$('.contact-form').on('change', (e) => {
  changeMethod($(e.currentTarget).val());
});

You need to move your code outside the change event, so I have kept your existing code within a method changeMethod.

Then call the method from to places

  1. From you change event method
  2. OnLoad of the JS file

Upvotes: 2

Related Questions