Two events in function - jQuery

Asked

Viewed 648 times

2

I have a function in jQuery which I do through the event .on('change') , but I also needed that same function to happen in page loading, but I don’t know how to do this, call two events in a function.

Code of function on jQuery:

$j("#fullname").on('change',function(){
    alert("Teste");
});
  • Can give a trigger in the statement itself $("#fullname").on('change',function(){alert("Teste");}).trigger('change');

2 answers

2

Create a trigger with the event after page loading:

$j(window).on("load", function(){
    $("#fullname").trigger("change");
});

This will trigger the event onchange in the element.

$(window).on("load", function(){
	$("#fullname").trigger("change");
});
$("#fullname").on('change',function(){
    alert("Teste");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="fullname">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

1


If I understand what you want, just create a função, so you can run it on page loading and on click, change or any other form you wish to perform.

function funcao(name){
  alert('Meu nome é: ' + name)
}

$('#btn').on('click', function(){
  funcao('Rafael Augusto')
})

funcao('Rafael Augusto')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Clique aqui</button>

  • Yes, that’s right. I did it the way you said it and it worked. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.