How to programmatically click Select element and trigger onChange handler? - javascript

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

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

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

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

How do you monitor a select tag?

I'm sure there is a very simple solution, I just don't know it...
I have a text box and a selector. The first option in the selection is custom, where they can input with the text box. If they select something else, the text box becomes disabled.
I'm guessing the solution will be to put an onclick to test the value, but is there another way?
Use the change event, not the click event.
var select = document.getElementById('mySelect'),
textbox = document.getElementById('myTextbox');
function onSelectChanged()
{
console.log(select.selectedIndex);
textbox.disabled = select.selectedIndex !== 0;
}
if (select.addEventListener)
{
select.addEventListener('change', onSelectChanged, false);
}
else
{
// !##$ing IE support, of course
select.attachEvent('onchange', onSelectChanged, false);
}
Demo: http://jsfiddle.net/mattball/pJMWN/
dont think onclick will serve your purpose better use onchange event in the selection and check for the selected value not equal to custom and then enable/disable your text box...
Hope this helps you,,,,
You would use an onchange listener on your select element. I also recommend using an onkeyup listener because some browsers do not fire onchange events when the user changes the select-box value using the keyboard. Here is some example code:
<select id="mySelect" name="name" onkeyup="this.onchange();" onchange="selectChanged(this);">
<option value="-1">(custom value)</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="text" id="customText" name="customOption" value="" />
<script>
window.selectChanged = function(theSelect) {
var textInput = document.getElementById("customText");
if (theSelect.selectedIndex == 0) {
textInput.disabled = undefined;
}
else {
textInput.disabled = true;
textInput.value = "";
}
};
</script>
Example: http://jsfiddle.net/tB2Am/2/

Categories