onchage event not working for autoselected value - javascript

I put selected="selected" for mail option. When the page is rendered, it should call the setImage function and display the image. But it is not happening, why?
JSFiddle
function setImage(select){
var image = document.getElementsByName("image-swap")[0];
image.src = select.options[select.selectedIndex].value;
}
<select name="kitchen_color" id="kitchen_color" onchange="setImage(this);">
<option value="https://www.google.ru/images/srpr/logo4w.png">Google</option>
<option value="http://yandex.st/www/1.645/yaru/i/logo.png">Yandex</option>
<option value="http://limg.imgsmail.ru/s/images/logo/logo.v2.png" selected="selected">Mail</option>
</select><br />
<img src="" name="image-swap" />

The answer is NO, the event you listen to is 'CHANGE' and there is no change since the page is loaded.
So, you will need to 'trigger' change event by yourself.
See example how to get what you want:
window.onload = function(){
var kitchen_color = document.getElementById('kitchen_color');
kitchen_color.onchange();
};
Or if you use jQuery:
$(document).ready(function(){
$('#kitchen_color').trigger('change');
});
http://jsfiddle.net/z2y24thk/

try this one after function declaration
$(document).ready(function(){
$('#kitchen_color').trigger('change');
});
here is updated jsfiddle
http://jsfiddle.net/NWbsj/76/

Related

.change() is not working because page is already loaded

jQuery(document).ready(function($){
$('#location').change(function(){
let selected_option = $(this).find(":selected").val();
$('#locationHeading').text(selected_option)
})
});
instead of waiting for a change on the #location which is a <select> I want to soon as the page loads do that function.
the reason being the selected option will already be selected once the page loads.
any help would be appreciated.
thanks
you can use .trigger()
jQuery(document).ready(function($){
$('#location').change(function(){
let selected_option = $(this).find(":selected").val();
$('#locationHeading').text(selected_option)
}).trigger('change') // <== add this
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="locationHeading"></h1>
<select id="location">
<option value="A">A</option>
<option value="B">B</option>
</select>
Put the change handler in a separate function, and call it in addition to adding the listener:
jQuery(function ($) {
const loc = $('#location');
const handler = () => {
let selected_option = loc.find(":selected").val();
$('#locationHeading').text(selected_option)
};
loc.on('change', handler);
handler();
});

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);
})

How to programmatically click Select element and trigger onChange handler?

For example, with the following code. I tried several solutions.
function handleChange() {
alert('hello')
}
<select id="names" onchange="handleChange()">
<option>Foo</option>
<option>Bar</option>
</select>
Solution 1.
document.getElementById('#select').selectedIndex = 1
This would change the value and display of select but doesn't trigger handleChange();
Solution 2
var element = document.getElementById('names');
var event = new Event('change');
element.dispatchEvent(event);
This returns true but still doesn't trigger handleChange();
Any ideas on how to do this? Or can it actually be done? Solution has to be javascript/html only and sadly no jQuery.
try this, it worked for me...your problem can just be you didnt change the actual value on solution 2 before triggering change :
function handleChange() {
alert('hello')
}
console.log(document.getElementById('names'));
document.getElementById('names').selectedIndex = 1;
document.getElementById('names').dispatchEvent(new Event('change'));
<select id="names" onchange="handleChange()">
<option>Foo</option>
<option>Bar</option>
</select>
Strange #KaelVergara, I copied your code and it is working for me
<script>
function handleChange123() {
alert('hello')
}
</script>
<select id="names123" onchange="handleChange123()">
<option>Foo</option>
<option>Bar</option>
</select>
<script>
var element = document.getElementById('names123');
var event = new Event('change');
element.dispatchEvent(event);
</script>
TRY THIS:
function handleChange()
{
alert('hello')
}
window.onload = function()
{
document.getElementById('names').selectedIndex = 1;
handleChange();
}
<select id="names" onchange="handleChange()>
<option>Foo</option>
<option>Bar</option>
</select>
one way would be as below from the below answer for another question here
Trigger change() event when setting <select>'s value with val() function
$('#selectField').val(10).change();
or simple one just to trigger the event
$('#selectField').change();
or if you do not want to use Jquery
you can use the below method
const $roomID = document.querySelector('.roomID')
$roomID.onchange = function () {
if ($("#ddlRoom").val() !== "") {
var ID = $("#ddlRoom").val();
console.log(ID);
} ;
};
$roomID.dispatchEvent(new Event('change'));

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