How to trigger a jquery function on page load? - javascript

I have the following function:
$('#borderColor').on('change', function() {
// update inventory
updateInventory(this.options[this.selectedIndex].text);
});
How can I automaticcally trigger this function when the page loads?

Just trigger the change event on the select on page load. This way you don't need to write duplicate code, and everything is handled at one place.
with $('#selector').trigger() you can trigger any event, like change, click, input, etc... you're listening to.
With $(document).ready(function() { /** your code here **/}) you can set code you wish to run after the page has finished loading and rendering.
function updateInventory(value) {
$('#inventory').text(value);
}
$('#borderColor').on('change', function() {
// update inventory
updateInventory(this.options[this.selectedIndex].text);
});
$(document).ready(function() {
$('#borderColor').trigger('change');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="borderColor">
<option value="red">red</option>
<option value="blue" selected="selected">blue</option>
</select>
<div id="inventory">
</div>

Did you heard the jquery trigger?
$(function() {
$('#borderColor').trigger('change')
});

Related

click event on HTML select element

I would like to listen a click event in the event. The change event is only fired when I select other items, but I need an event to be triggered even I click the selected one.
For example, when I select Apple, change event triggered. Then I select Apple again, I need an event to be triggered as well.
$("#fruit").on('click', function() {
console.log("click event");
});
$("#fruit").on('change', function() {
console.log("change event");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="fruit">
<option>Apple</option>
<option>Pear</option>
</select>
I solve that problem wrapping the select element with a div element and using the onclick over the div, after that the function javascript call the select element using the id, like this:
HTML:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<div onclick="ReadSelected()">
<select id="fruit">
<option value="Apple">Apple</option>
<option value="Pear">Pear</option>
</select>
</div>
Javascript:
function ReadSelected(){
var selectedValues = $("#fruit").val();
console.log(selectedValues); //if you select apple will be ['Apple']
}
According to the jQuery docs:
The change event is sent to an element when its value changes. This event is limited to elements, boxes and elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
As there is no change when you click on 'Apple' when 'Apple' is already selected, it looks like the 'click' event is your best option. Why exactly do you need the change event to fire when you click the same option? Maybe there is a better solution than firing the change event in this case?
You may check condition on click like below to achieve what you want .
var flag = false;
$('#fruit').on('click', function() {
if (flag) {
console.log($(this).val());
flag = false;
} else {
flag = true;
}
}).on('blur', function() {
flag = false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="fruit">
<option>Apple</option>
<option>Pear</option>
</select>

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.
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');
});
$(document).ready(function(){ employmentGroups($( ".emp-status-id" )); })
Looking for this?
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

Why select on change method doesn't work?

I try to call a function when a value from the select box is chosen. I would also have a default value selected and a button appear for that value on the page.
This is my select box:
<select id="messagingMode" class="bootstrap-select" >
<option value="1" selected="selected">Webhooks messaging</option>
<option value="2">Real time messaging</option>
</select>
This is the js:
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn(this));
And the function just prints the selected value for the moment:
function showCorrespondingAuthorizationBtn(select) {
console.log(select.val());
}
Nothing is printed in the console, why doesn't this work?
Try with direct call function name not with function() .Default bind with this in change function
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn);
function showCorrespondingAuthorizationBtn() {
console.log($(this).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="messagingMode" class="bootstrap-select">
<option value="1" selected="selected">Webhooks messaging</option>
<option value="2">Real time messaging</option>
</select>
You are invoking the function, not passing it as reference. Also this is not what you think it is in that context.
Try:
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn);
function showCorrespondingAuthorizationBtn(event) {
console.log($(this).val());
// or
console.log(this.value);
}
Use the jQuery event delegation:
$('#messagingMode').on('change',function(){
console.log($(this).val());
});
Here is a working fiddle.
$('#messagingMode').change(function () {
showCorrespondingAuthorizationBtn($(this).val());
});
It is not triggering because your are invoking the method on your event attachment logic.
// calling the invocation operator () triggers the method
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn(this));
In order to solve this, try the following code.
function onDropdownChanged() {
var sender = $(this);
console.log(sender.val());
}
$(document).ready(function() {
$('#messagingMode').on("change", onDropdownChanged);
})

order of Events for Select element in html

I only tested this so far in chrome browser.
I have the html select element below defined:
HTML
<select class="ddl" size="5">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
I have the following script:
Javascript + jQuery
$(document).ready( function () {
$('.ddl').change( function () { alert('ddl changed'); });
$('.ddl').click( function () { alert('ddl clicked'); });
});
In the browser,
- if you quickly click on an item in the list box, you will see that the order of events start with change then click.
- if you hold the mouse down for a 10 seconds then release it (long press), click fires then change.
jsFiddle
I change the code to below script (add mouseup event),
Javascript + jQuery
$(document).ready( function () {
$('.ddl').change( function () { alert('ddl changed'); });
$('.ddl').click( function () { alert('ddl clicked'); });
$('.ddl').mouseup( function () { alert('ddl mouseup'); });
});
I get mouseup, change, then click regardless of the speed of the click.
jsFiddle
Isn't the order of events supposed to stay the same? Is this a chrome bug?
UPDATE
In firefox, change, mouseup, and then clicked on a fast click, and only click event is eliminated on a slow click.
In IE11, change then click is fired on fast click, only mouseup is fired on slow click.
UPDATE with adeneo's suggestion:
jsFiddle1
Javascript + jQuery
$(document).ready( function () {
$('.ddl').change( function () { console.log('ddl changed'); });
$('.ddl').click( function () { console.log('ddl clicked'); });
});
Chrome: no change
Firefox: no change
IE11: no change
jsFiddle2
Javascript + jQuery
$(document).ready( function () {
$('.ddl').change( function () { console.log('ddl changed'); });
$('.ddl').click( function () { console.log('ddl clicked'); });
$('.ddl').mouseup( function () { console.log('ddl mouseup'); });
});
Chrome: no change
Firefox: no change
IE11: no change
UPDATE based on Wesley Murch's suggestion:
I have a software package that I am working with. The software package generates HTML dynamically (template driven). The feature I am working on is Cascading dropdowns. There are some dropdowns in that have attributes to show hierarchy. To build the the dependency, I thought I would bind to the change event and call a webservice to update the child dropdown. Now the dilemma I have is that there is pre-existing code that binds to various events. I think the pre-existing code has some code that stops processing of subsequent events. I cannot change that code at the time being. I always thought that the change event is triggered before the click event. It works fine if you do a quick click in chrome, but if you hold your mouse down while you think of the selection for a couple seconds my code for cascading dropdown does not get called.
Sorry for the lengthy explanation.
<script>
$(document).ready(function () {
$('.ddl').change(function () {
console.log("change");
});
$('.ddl').click(function () {
console.log("click");
});
});
</script>
<select class="ddl" size="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
order
click select.html:15
change select.html:11
2
click select.html:15
change select.html:11
click

Javascript onchange on select inside script

I'm learning Javascript, and here's what I'm trying to do...
<body>
<select name="selTitle" id="titles">
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
</select>
</body>
and for the script,
<script type='text/javascript'>
var title = document.getElementById("titles");
title.onchange = function() {
alert("Hi");
}
</script>
But its not working, am I doing something wrong? Here's the demo.. http://jsfiddle.net/jq9UA/10/
Wrap your code in onload event:
window.onload = function(){
var titles = document.getElementById("titles");
titles.onchange = function() {
alert("Hi");
}
};
Working Demo
This makes sure that select box is actually available to apply events to which you can do using onload event or puting your script at bottom of your page just before </body> tag.
its working fine.
just change the options like this:

Categories