given:
<select id="mySelect">
<option>..</option>
...
</select>
Using the select id, how can I trigger a click event on one of the options? I tried attaching the event directly to the select, but this triggers an event whenever the select is clicked on (even if there are no options). Oh, and it is a multi-select (although I don't think that matter).
You want the 'change' event handler, instead of 'click'.
$('#mySelect').change(function(){
var value = $(this).val();
});
$('#mySelect').on('change', function() {
var value = $(this).val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<select id="mySelect">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
</select>
EXAMPLE
you can attach a focus event to select
$('#select_id').focus(function() {
console.log('Handler for .focus() called.');
});
The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.
I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:
let blockChange = false;
$element.keydown(function (e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// prevents select opening when enter is pressed
if (keycode === 13) {
e.preventDefault();
}
// lets the change event know that these keypresses are to be ignored
if([38, 40].indexOf(keycode) > -1){
blockChange = true;
}
});
$element.keyup(function(e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// handle enter press
if(keycode === 13) {
doSomething();
}
});
$element.change(function(e) {
// this effective handles the click only as preventDefault was used on enter
if(!blockChange) {
doSomething();
}
blockChange = false;
});
You can also try this to get previous value of select and the clicked value.
HTML
<select name="status">
<option value="confirmed">confirmed</option>
<option value="packed">packed</option>
<option value="shiped">shiped</option>
<option value="delivered">delivered</option>
</select>
script
var previous;
$("select[name=status]").focus(function () {
previous = this.value;
}).change(function() {
var next = $(this).val()
alert("previous: "+previous+ " and Next: "+ next)
previous = this.value;
});
<select name="data" id = 'cohort' class="form-control" style = "width:215px; margin-left:20px; margin-bottom:8px ; height:30px" >
<option value = 0>All</option>
<option value = 1>Diseases</option>
<option value = 2>Drugs</option>
<option value = 3>Procedures</option>
</select>
const element = document.getElementById("cohort");
const event = new MouseEvent("mousedown");
element.dispatchEvent(event);
What I have done in this situation is that I put in the option elements OnClick event like this:
<option onClick="something();">Option Name</option>
Then just create a script function like this:
function something(){
alert("Hello");
}
UPDATE:
Unfortunately I can't comment so I'm updating here
TrueBlueAussie apparently jsfiddle is having some issues, check here if it works or not: http://js.do/code/klm
its working for me
<select name="" id="select">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
<script>
$("#select > option").on("click", function () {
alert(1)
})
</script>
One possible solution is to add a class to every option
<select name="export_type" id="export_type">
<option class="export_option" value="pdf">PDF</option>
<option class="export_option" value="xlsx">Excel</option>
<option class="export_option" value="docx">DocX</option>
</select>
and then use the click handler for this class
$(document).ready(function () {
$(".export_option").click(function (e) {
//alert('click');
});
});
UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome.
Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.
Related
given:
<select id="mySelect">
<option>..</option>
...
</select>
Using the select id, how can I trigger a click event on one of the options? I tried attaching the event directly to the select, but this triggers an event whenever the select is clicked on (even if there are no options). Oh, and it is a multi-select (although I don't think that matter).
You want the 'change' event handler, instead of 'click'.
$('#mySelect').change(function(){
var value = $(this).val();
});
$('#mySelect').on('change', function() {
var value = $(this).val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<select id="mySelect">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
</select>
EXAMPLE
you can attach a focus event to select
$('#select_id').focus(function() {
console.log('Handler for .focus() called.');
});
The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.
I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:
let blockChange = false;
$element.keydown(function (e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// prevents select opening when enter is pressed
if (keycode === 13) {
e.preventDefault();
}
// lets the change event know that these keypresses are to be ignored
if([38, 40].indexOf(keycode) > -1){
blockChange = true;
}
});
$element.keyup(function(e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// handle enter press
if(keycode === 13) {
doSomething();
}
});
$element.change(function(e) {
// this effective handles the click only as preventDefault was used on enter
if(!blockChange) {
doSomething();
}
blockChange = false;
});
You can also try this to get previous value of select and the clicked value.
HTML
<select name="status">
<option value="confirmed">confirmed</option>
<option value="packed">packed</option>
<option value="shiped">shiped</option>
<option value="delivered">delivered</option>
</select>
script
var previous;
$("select[name=status]").focus(function () {
previous = this.value;
}).change(function() {
var next = $(this).val()
alert("previous: "+previous+ " and Next: "+ next)
previous = this.value;
});
<select name="data" id = 'cohort' class="form-control" style = "width:215px; margin-left:20px; margin-bottom:8px ; height:30px" >
<option value = 0>All</option>
<option value = 1>Diseases</option>
<option value = 2>Drugs</option>
<option value = 3>Procedures</option>
</select>
const element = document.getElementById("cohort");
const event = new MouseEvent("mousedown");
element.dispatchEvent(event);
What I have done in this situation is that I put in the option elements OnClick event like this:
<option onClick="something();">Option Name</option>
Then just create a script function like this:
function something(){
alert("Hello");
}
UPDATE:
Unfortunately I can't comment so I'm updating here
TrueBlueAussie apparently jsfiddle is having some issues, check here if it works or not: http://js.do/code/klm
its working for me
<select name="" id="select">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
<script>
$("#select > option").on("click", function () {
alert(1)
})
</script>
One possible solution is to add a class to every option
<select name="export_type" id="export_type">
<option class="export_option" value="pdf">PDF</option>
<option class="export_option" value="xlsx">Excel</option>
<option class="export_option" value="docx">DocX</option>
</select>
and then use the click handler for this class
$(document).ready(function () {
$(".export_option").click(function (e) {
//alert('click');
});
});
UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome.
Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.
I have form. I want to do something, if the certain option is selected. I try this
if (document.getElementById('order-select').value == "Услуга") {
alert("blabla");
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="order-select">
<option value="Услуга" class="item-1">Услуга</option>
<option value="Строительный проект" class="item-2">Строительный проект</option>
</select>
Problem : I want to alert every time, when option is selected.
Need help
You need to attach an event listener for the change event.
When the event is fired, you can access the element through the target object on the event object.
document.getElementById('order-select').addEventListener('change', function (e) {
if (e.target.value === "Услуга") {
alert('Selected');
}
});
<select id="order-select">
<option class="item-1">--Select--</option>
<option value="Услуга" class="item-2">Услуга</option>
<option value="Строительный проект" class="item-3">Строительный проект</option>
</select>
Updated Example
document.getElementById('order-select').addEventListener('change', function (e) {
if (e.target.value === "Услуга") {
alert('Selected');
}
});
Drop down not working when I select same option second time.
This is my code:
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
alert(x);
}
</script>
</body>
</html>
First time select any care eg:Audi, then it alerts Audi, after alert again select Audi then there is no alert coming. Could anybody help me whats wrong in this?
Since you select the same option TWICE so there is no change in selected object of Dropdown.
Try like below
Updated Answer
var dd = document.getElementById('mySelect');
var storeLstSlct = document.getElementById('checkIndx');
var slctdValue = '';
if(dd.selectedIndex == 0)
{
return false;
}else if(storeLstSlct.value == dd.options[dd.selectedIndex].value)
{
storeLstSlct.value = 'garbage';
return false;
}else
{
slctdValue = dd.options[dd.selectedIndex].value;
alert(slctdValue);
storeLstSlct.value = slctdValue;
}
Fiddle is HERE
The event is onchange when you try to select the item already selected change event wont fire.
Are you looking for this??
Add the following code
$('option').click(function(){
alert($(this).text());
});
Unfortunately, the above method will not work in "Chrome", try in "Internet Explorer" or "Mozialla" (atleast IE is being used for this reason :p )
you forgot to close option tags and to do this you need to attach onclick event handler to all of the options in the dropdown, see below:
var x = document.getElementById("mySelect");
//attach onclick event handlers to options
for (var i = 0; i < x.options.length; i++)
{
if (x.options[i].addEventListener)
{
/*all other browsers*/
x.options[i].addEventListener("click", function() {mysFunction(this)}, false);
}
else if (x.options[i].attachEvent) /*ie < 9*/
{
x.options[i].attachEvent("click", function() {mysFunction(this)});
}
}
//execute my alert box on item select
function mysFunction(elem) {
alert(elem.value);
}
<select id="mySelect">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
Update with Demo : http://jsbin.com/hujavalayu/1/edit
I hope this will satisfy your requirement, Please check the link
Trigger the event when selected the same value in dropdown?
<p>Select a new car from the list.</p>
<select id="ddList" onClick="onSelect()">
<option value="0">Select Me</option>
<option value="List1">List1</option>
<option value="List2">List2</option>
<option value="List3">List3</option>
</select>
<script>
var prevIndex = "";
function onSelect() {
var currIndex = document.getElementById("ddList").selectedIndex;
if (currIndex > 0) {
if (prevIndex != currIndex) {
alert("Selected Value = " + document.getElementById("ddList").value);
prevIndex = currIndex;
} else {
prevIndex = "";
}
}
}
</script>
you should use onclick="this.value=null" and define your onchange as well,
so every time you select any option it will clear the selected item and you can select same option again ;).
Here is the sample Code:
$serial_no = 0;
<select id="<?php echo $serial_no++; ?>" onclick="this.value=null" onchange="update_value(this.value,this.id)" class="form-control" required>
<option><?php echo $row['card']; ?></option>
<option>---------</option>
<option>Pending</option>
<option>Deliver</option>
</select>
update_value(item){
alert(item);
}
I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};
I have constructed a dynamic select using jQuery like below:
Based on YesOrNo, I have to show/hide options in Source and Type
Yes/No Source Type
---------------------------------------------
Yes Yes1 and Yes2 Yes
No No1 and No2 No1 to 6
HTML:
<select id="YesOrNo" name='YesOrNo'>
<option value=''>Select Yes/No</option>
<option value='1'>Yes</option>
<option value='2'>No</option>
</select>
<select id='Source' name='Source'>
<option value=''>Select Source</option>
<option data-aob='Yes' value='1'>Yes1</option>
<option data-aob='Yes' value='2'>Yes2</option>
<option data-aob='No' value='3'>No1</option>
<option data-aob='No' value='4'>No2</option>
</select>
<select id="Type" name='Type'>
<option value=''>Select Type</option>
<option data-aob='No' value='1'>No1</option>
<option data-aob='No' value='2'>No2</option>
<option data-aob='No' value='3'>No3</option>
<option data-aob='No' value='4'>No4</option>
<option data-aob='Yes' value='5'>Yes</option>
<option data-aob='No' value='6'>No5</option>
<option data-aob='No' value='7'>No6</option>
</select>
JQuery:
$('#YesOrNo').on('change', function () {
if (this.value === '1') {
$('#Source option[data-aob=Yes]').show();
$('#Source option[data-aob=No]').hide();
$('#Type option[data-aob=Yes]').show();
$('#Type option[data-aob=No]').hide();
$("#Source option:selected").prop("selected", false);
$("#Type option:selected").prop("selected", false);
} else if (this.value === "2") {
$('#Source option[data-aob=Yes]').hide();
$('#Source option[data-aob=No]').show();
$('#Type option[data-aob=Yes]').hide();
$('#Type option[data-aob=No]').show();
$("#Source option:selected").prop("selected", false);
$("#Type option:selected").prop("selected", false);
} else {
$('#Source option').show();
$('#Type option').show();
$("#Source option:selected").prop("selected", false);
$("#Type option:selected").prop("selected", false);
}
});
Here is my JSFiddle
This is working perfect as I expected. Since the values are obtained from database, I have a problem while displaying the selected option in YesOrNo.
<select id="YesOrNo" name='YesOrNo'>
<option value=''>Select Yes/No</option>
<option selected value='1'>Yes</option>
<option value='2'>No</option>
</select>
Here the option "Yes" is selected by default, but here http://jsfiddle.net/ubVfa/1/ still showing the four options and Type showing all 7 options.
Yes/No Source Type
--------------------------------------------------------------------
Yes(SELECTED by default) All 4 options All 7 Options
How to tune my code to update the options in select dynamically.
Any help is appreciated.
You can call $("...").change() after the page is loaded:
$(function(){
$('#YesOrNo').change();
});
See my fiddle:
I also hid the options when nothing is selected, calling $("...").hide() in the "onchange" event handler.
The $(func) with func as an anonymous function is a syntatic suggar for $(document).ready(func), which calls that given function after loading.
The "change" call is just a trigger call, like $("...").trigger("change").
You can use trigger to manually invoke the handler on page load.... still your solution will not work in IE... see further changes below
var sourceHtml = $('#Source').html();
var typeHtml = $('#Type').html();
$('#YesOrNo').on('change', function () {
var sources = $(sourceHtml);
var types = $(typeHtml);
var aob = $(this).find('option:selected').data('aob');
if(aob){
sources = sources.filter('[data-aob="' + aob + '"]');
types = types.filter('[data-aob="' + aob + '"]');
}
$('#Source').empty().append(sources)
$('#Type').empty().append(types)
}).triggerHandler('change');
Demo: Fiddle
You can simply do this by triggering change event on load.
just add below code inside document.ready
$('#YesOrNo').trigger('change');
and for test it add selected="selected" for No option and run the code.
See Demo
If your code logic allows this trigger a change event once.
//Triggering a change event on document ready
$(document).ready(function(){
$('#YesOrNo').trigger('change');
});
JS FIDDLE