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

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

Related

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

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

onchage event not working for autoselected value

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/

jQuery - Find Val of Select Box and print to body class

I'm trying to write a small script that prints the value of a select box to the body class.
I'm hoping to have it so that when the value changes it auto swaps the old class for the new class (value) Here is a js fiddle of the script i'm working on for it.
It is changing the class just fine but not finding the initial value of the select box on page load.
Any help would be awesome!
http://jsfiddle.net/BMsP8/
jQuery(document).ready(function () {
// On load
jQuery(document).ready(function () {
if (jQuery("select[name=mySelections] option:selected").val() == 'myvalue') {
jQuery("#page_template");
}
});
jQuery('#page_template').change(function () { // on change event
jQuery('body')
//.removeClass() // remove the classes on the body
// or removeClass('class1 class2 ...') in order to not affect others classes
.addClass(jQuery(this).val()); // set the new class
})
I think problem is in your selector try this,
if (jQuery("#page_template").val() == 'myvalue') {
alert(jQuery("#page_template").val());
}
Also you can use toggleClass() instead of addClass() or removeClass() like,
jQuery('#page_template').change(function () { // on change event
jQuery('body').toggleClass(jQuery(this).val()); // toggle the class
});
Demo
set your html
<select id="page_template">
<option value="Default">Default</option>
<option value="class1">First Class</option>
<option value="class2">2nd Class</option>
</select>
in jS
$(document).ready(function(){
alert($("#page_template").val());
if ($("#page_template").val() == 'Default') {
$('body').addClass($("#page_template").val());
}
$('#page_template').change(function () { // on change event
$('body').removeClass().addClass($(this).val()); // set the new class
})
});
demo
Try this:
jQuery('#page_template').change(function () { // on change event
var cls = jQuery(this).val();
jQuery('body').removeAttr("class");
jQuery('body').addClass(cls); // set the new class
});
Fiddle here.
Hope this helps
**HTML**
<select id="page_template">
<option value="myvalue">Default</option>
<option value="class1">First Class</option>
<option value="class2">2nd Class</option>
</select>
**JS**
jQuery(document).ready(function () {
if (jQuery("#page_template option:selected").val() == 'myvalue') {
jQuery('body').addClass(jQuery("#page_template option:selected").val());
}
jQuery('#page_template').change(function () { // on change event
jQuery('body').removeAttr("class");
jQuery('body').addClass(jQuery(this).val()); // set the new class
});
})

jQuery click event not working on option element

Why doesn't the following code work?
$('select option').live('click', function(){
alert('hello')
})
html:
<select class="ok">
<option>5</option>
</select>
EXAMPLE: http://jsfiddle.net/fQxj7/2/
Do this instead:
$('select').change(function(){
alert('hello');
});
If you need to know the selected value inside the event handler, then you can do this:
$('select').change(function() {
var selectedOption = $(this).val();
});
http://jsfiddle.net/FishBasketGordo/2ABAh/

Categories