How to trigger click event on select element? (not change) - javascript

In the following code when I change the selection, there will be an alert. I am trying to make the function like when I click on the option then it will show an alert.
$(document).ready(function() {
$("#x").change(function() {
alert("Haha");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="x">
<option selected>A</option>
<option>B</option>
<option>C</option>
</select>
In the below code there is no effect when I click on the options already selected options. for example a is selected then i click a is no effect.
$(document).ready(function() {
$("#x").on("option", "click", function() {
alert("Haha");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="x">
<option selected>A</option>
<option>B</option>
<option>C</option>
</select>
because i want to trigger event while i re-clicking the selected option.
click selection box->drop menu->click selected option->trigger event
Can anyone help me?

"click selection box->drop menu->click selected option->trigger event"
First of all do not use alert(), it prompts for an extra click you really don't need to waste your time on. Use console.log().
The following demo:
Delegates the click event to select#x:
$('#x').on('click',...
Once clicked, it will trigger a focus event on every even click✱:
✱ if (cnt % 2 === 0) { $(this).trigger('focus');}
select#x is also delegated to the focus event and will call optionTrigger():
$('#x').on('focus', optionTrigger);
function optionTrigger() will log the selected <option> index and text:
✱ if (cnt < 2) {...
...$(this).trigger('blur'); }
var idx = $(this)[0].selectedIndex;
var txt = $(this).find('option').eq(idx).text();
Demo
var cnt = 1;
$("#x").on("click", function(e) {
if (cnt % 2 === 0) {
$(this).trigger('focus');
}
cnt++;
});
$('#x').on('focus', optionTrigger);
function optionTrigger(e) {
if (cnt < 2) {
$(this).trigger('blur');
} else {
var idx = $(this)[0].selectedIndex;
var txt = $(this).find('option').eq(idx).text();
console.log(idx + ': ' + txt);
}
}
<select id="x">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Have you tried bind with select e.g.:
$('#x').bind('click', function(){
console.log('Clicked')
});
If this doesn't work do tell. Thanks
Hope this helps.

Do you need to execute your code while clicking on Dropdown???
If Yes, here is the code for you
https://jsfiddle.net/shoesheill/gjLyxo5d/6/
If not please leave a comment along with your requirements.
$(document).ready(function() {
$("#x").off().on('click',function() {
alert("Haha");
});
});

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

How to stop a select menu form opening or changing?

$('#selectmenu').on('keyup focus mousedown', function(e) {
e.preventDefault();
});
but when it is selected by pressing tab i can change the value by pressing up & down key.how to stop it?
Block the tab key.
$('/*The Previous Input */').on('keydown', function(e) {
if (e.keyCode == 9) {
e.preventDefault();
}
});
I don't have your HTML, so i can't test or integrate the code.
You also can use disabled="disabled", i think is a better solution.
You use off() or unbind() methods of jQuery:
<select id="dropDown" name="dropDown" style="margin-top: 5px; width: 150px;">
<option value="select">Select </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="All">All </option>
</select>
<button id="stopChange" >Stop</button>
<button id="StartChange" >Start</button>
jQuery code:
$("#stopChange").click(function () {
$("#parSelCategor").unbind("change");
});
$("#StartChange").click(function () {
$("#parSelCategor").bind("change");
});
You may listen you a more global event like 'onchange' and change the value back to the previous one when the event trigger.
Disabling the select may work too.
Edit : 'keydown' seems like a good idea too.
you can change the tabindex of the select box
$('#selectmenu').attr('tabindex', -1).on('keyup focus mousedown', function (e) {
e.preventDefault();
});
or best way is just disable the control
$('#selectmenu').attr("disabled", true);
Demo
Here's a solution that simply forces the selection to stay the same if some variable (stopChange) is true.
JS (jQuery):
var stopChange = true;
var opt = $('option:selected');
$('#selectmenu').on('change', function () {
if (stopChange) {
opt.attr('selected', true);
}
});
Here's a fiddle.

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