10

I want to run a script on page load first time (for default value of select element), and then on each change of select element. Is it possible to do it in one line, or do I need to duplicate function for this events?

I know that I can use next structure:

$('#element').on('keyup keypress blur change', function() {
    ...
});

But it doesn't seem to support load event.

Any ideas?

4 Answers 4

11

If i understand what you mean, just trigger any one of these events:

$('#element').on('keyup keypress blur change', function() {
    ...
}).triggerHandler('keyup'); //or trigger('keyup') or keyup() which then let event propagate
Sign up to request clarification or add additional context in comments.

2 Comments

It is definitely the simplest way from suggested, so I accept this answer.
This looks promising but I am selecting multiple elements at the same time ($('.foo')) and the trigger only seems to fire for the first element…
6

Instead of using anonymous functions (defining them right where they will be used) you could just create a regular function and tell jQuery to call it when those events happen.

$(document).ready(myFunction);
$('#element').on('keyup keypress blur change', myFunction);

function myFunction() {
    // Do something here...
}

Comments

5

for change element use your :

$('#element').on('change', function() {
    ...
});

and to use same function on load first time use structure like:

jQuery(window).on("load", function(){

  $('#element').change();

});

to call the same function

Comments

0

$('#element').on('keyup keypress blur change', function() {
  console.log($(this).val());
}).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="element">
  <option value="">Select</option>
  <option value="1">BMW</option>
  <option value="2">HONDA</option>
  <option value="3">FORD</option>
</select>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.