Detect when a specific <option> is selected with jQuery - javascript

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 #

Related

Select2 Dropdown Multiple select and unselect

I have a select2 dropdown with 4 options code is:
<select id="ddlInqOn" class="InqSelect2 form-control">
<option value="1">--All--</option>
<option value="2">Today Date</option>
<option value="3">Past Date</option>
<option value="4">Feature Date</option>
</select>
select2 called by this javascript:
$('.InqSelect2').select2({
dropdownAutoWidth: 'true',
multiple: true
});
I want to achieve like when I click all option then remove other options and if other option is selected then remove all option from selection.
I have tried this code:
$('body').on('change', '#ddlInqOn', function() {
debugger;
//
});
but the change event is not triggred so any other possibility to track change event of select2 dropdown?
Select2 uses the jQuery event system. So you can attach to the select2 events using the JQuery on method.
Then you can set the value of the select element and trigger the change event to update the select box.
You can do what you have asked in following way.
$('.InqSelect2').on('select2:select', function (e) {
if (e.params.data.id == 1){
$(this).val(1).trigger('change');
}else{
values = $(this).val();
var index = values.indexOf('1');
if (index > -1) {
values.splice(index, 1);
$(this).val(values).trigger('change');
}
}
});
Note that I have used '1' as the value of --All-- option. Feel free to ask me anything if it's not clear to you.
https://jsfiddle.net/c6yrLoow/
Hope it helps :)
Answer given by #Nimeksha works perfectly in jsfiddle given by # Nimeshka but in my code i cant get trigger event of change in dropdown and after searching i found solution from here. the code is here :
$(document).on('change', '.InqSelect2', function () {
debugger;
if (e.params.data.id == 1) {
$(this).val(1).trigger('change');
} else {
values = $(this).val();
var index = values.indexOf('1');
if (index > -1) {
values.splice(index, 1);
$(this).val(values).trigger('change');
}
}
});
i have also tried :
$('body').on('change', '.InqSelect2', function () {
debugger;
if (e.params.data.id == 1) {
$(this).val(1).trigger('change');
} else {
values = $(this).val();
var index = values.indexOf('1');
if (index > -1) {
values.splice(index, 1);
$(this).val(values).trigger('change');
}
}
});
but it doesn't work. also by id #ddlInqOn does not work.
why above code worked with $(document).on('change', '.InqSelect2', function () {}); worked i dont know but it works for me.
thanks again #Nimeshka

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

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 Option De-Select Event?

I would like to detect the event where an option is de-selected from a select element. So for instance, if my HTML is:
<select id="select_box">
<option value="1">Hot</option>
<option value="2">Cold</option>
<option value="3">Just Right</option>
</select>
And the second option is selected (value="2"), and then the user de-selects it by clicking on another option (such as value="3") or clicking the same option again, how do I detect that event using jQuery? My goal is to fire off a function when it happens.
I tried the following:
$("#select_box option:selected").change(function() {
console.log($(this).val());
});
But it didn't work.
The change event should go on the select element itself:
$("#select_box").change(function() {
console.log($(this).val());
});
This event fires when the value of the select is changed and will match the behaviour you require.
I want the value of the option that was de-selected.
In that case you would need to store the previous value when it's selected, something like this:
$("#select_box").change(function() {
var $select = $(this),
currentValue = $select.val(),
oldValue = $select.data('previous-value');
// do stuff...
$select.data('previous-value', currentValue);
});
Well, this is how I would handle this with with a change Event listener.
$("#select_box").on('change', function(e){
var $t = $(this), data = $t.data('last') || {optText:'none', val:'none'};
$t.next().text('last was ['+data.optText+'] and its value is "'+data.val+'"').end()
.data('last', {optText:$t.children('[value="'+$t.val()+'"]').text(), val:$t.val()});
});
Fiddle HERE
I would enable the element when the option is selected using the one() event binding method
change event will fired only when value is changed which is required by you
$("#select_box").change(function() {
console.log(this.value);
});
You can do it manually some thing like below code i given,
var xSelectedOption = 0;
$("#select_box").change(function() {
if(xSelectedOption != $(this).val())
{
xSelectedOption = $(this).val();
console.log("Option was changed!");
}
});

Categories