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

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

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

How can I change selected value of a DropDownList with having change method?

I was wondering if it's possible to get jQuery to select an option with having predefined change method.
Let me give me an example; I have a drop-down list like this:
<select id="ddl_BankRequestType">
<option>-- Request Type ---</option>
<option value="val1">Item1</option>
<option value="val2">Item2</option>
</select>
If user selects Item1 or Item2 some logic will be executed:
$('#ddl_BankRequestType').change(function () {
var selectedItem = $(this).find(":selected").text();
if (selectedItem === 'Item1') {
// codes
} else if (selectedItem === 'Item2') {
//other codes
}
});
It works like a charm. Now in document.ready I want the second option be selected item, so I put this code:
$('#ddl_BankRequestType > option:eq(2)').attr('selected', true);
It also works, but I want the logic for Item2 to execute. I have tried the following, but they do nothing:
$('#ddl_BankRequestType > option:eq(2)').attr('selected', true).change();
$('#ddl_BankRequestType > option:eq(2)').attr('selected', true).trigger('change');
You can check the code from DEMO
$(function (){
$('#ddl_BankRequestType').change(function () {
var selectedItem = $(this).find(":selected").text();
console.log(selectedItem)
if (selectedItem === 'Item1') {
alert('item1');
} else if (selectedItem === 'Item2') {
alert('item2');
}
});
$('#ddl_BankRequestType > option:eq(2)').attr('selected', true).change();
});
A quick fix should be something like below,
$('#ddl_BankRequestType').on("change",function () {
var selectedItem = $(this).find(":selected").text();
if (selectedItem === 'Item1') {
doItem1();
} else if (selectedItem === 'Item2') {
doItem2();
}
});
function doItem1(){
alert('Item1');
//other codes
}
function doItem2(){
alert('Item2');
//other codes
}
$(document).ready(function(){
$('#ddl_BankRequestType > option:eq(2)').attr('selected', true);
doItem2();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddl_BankRequestType">
<option>-- Request Type ---</option>
<option value="val1">Item1</option>
<option value="val2">Item2</option>
</select>
The problem is .attr() returns a string. So, you can't chain it to trigger the change event. You could do the following:
var ddl_BankRequestType = $('#ddl_BankRequestType');
ddl_BankRequestType.find('option:eq(2)').attr('selected', true);
ddl_BankRequestType.trigger('change');
This is likely a timing issue - since theoretically your code should be firing that trigger event based on the way you're doing it. I think it's simply firing the event before the change function is registered. jQuery's Document load lifecycle loops through all of the defined loaders in the order they're registered, so if you're not able to change when you set the option element as "selected" to after the change event is bound, you may be able to use the native timeout function to ensure it gets fired last.
I generally avoid using timeout like this, but in your scenario it may work:
setTimeout(function() { /* Set the option element true here */ }, 1000);
Best bet is to try and set the element after the change event is bound.

html form reset not doing triggering select onchange

I am having a form where the fields need to change according to my select.
But when I hit the reset the select resets back to default, but the onchange event on the select is not triggered. Is there anyway so that I can add that to my javascript?
I am resetting using a button with type="reset"
$('#newHistoryPart select[name="roundType"]').on('change', function (data)
{
$(".answerType").hide();
selected = $(this).find("option:selected").val();
roundTypeChange(selected);
});
From my comment above, use onreset event instead of onchange:
$('#yourform').on('reset', function(){
// do something
});
What you need to do is, trigger the change event manually when the reset button is clicked. See Fiddle here
$('select').on('change', function ()
{
alert('on change');
});
$('input[type="reset"]').click(function() {
$("select").trigger('change');
});`
you can use
$('select[name="roundType"]').prop('selectedIndex',0);
DEMO HERE
This may help you, replace alert lines with your activity code.
JSFiddle
HTML
<select name="opt" onchange="getval(this)">
<option value="Select" selected disabled>Select</option>
<option value="op1">Option 1</option>
<option value="op2">Option 2</option>
</select>
JavaScript
function getval(sel) {
if (sel.value == "op1") {
alert("Option 1 Selected");
} else if (sel.value == "op2") {
alert("Option 2 Selected");
}
else
{
alert("EXCEPTION !");
}
}

Detect when a specific <option> is selected with jQuery

I'd like jQuery to detect when the option with the id trade_buy_max is selected.
$(document).ready(function() {
$("option#trade_buy_max").select(function () {
//do something
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<select name='type' id='type'>
<option id='trade_buy' value='1' selected='selected'>Buy</option>
<option id='trade_buy_max' value='1'>Buy max</option>
<option id='trade_sell' value='2'>Sell</option>
<option id='trade_sell_max' value='2'>Sell max</option>
</select>
I've tried the following, but it doesn't seem to work.
Any ideas?
This works...
Listen for the change event on the select box to fire and once it does then just pull the id attribute of the selected option.
$("#type").change(function(){
var id = $(this).find("option:selected").attr("id");
switch (id){
case "trade_buy_max":
// do something here
break;
}
});
What you need to do is add an onchange handler to the select:
$('#type').change(function(){
if($(this).val() == 2){
/* Do Something */
}
});
you can bind change event on its select instead, then check if option selected
$("select#type").change(function () {
if( $("option#trade_buy_max:selected").length )
{
// do something here
}
});
$("option#trade_buy_max").change(function () {
opt = $(this).children("option:selected").attr('id');
if(opt == '#trade_sell_max'){
// do stuff
}
});
Untested, but that should work.
Use the change event and get the id attribute of the selected option:
$('#type').change(function () {
var selectedId = $('option:selected', this).attr('id');
if (selectedId == "trade_buy_max") {
// do something
}
});
Change .select to .change and put space before #

Categories